需要sql生成预期结果中显示的输出

cs7cruho  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(217)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

10个月前关门了。
改进这个问题

Customer | Add Seq | City     | Phone
Test1    | 1       |Delhi     | 1231
Test1    | 2       |Noida     | 2334
Test2    | 1       |Bengaluru | 3333
Test2    | 2       |Noida     | 3333
Test2    | 3       |Chennai   | 5565
Test3    | 2       |Chennai   | 5565
Test4    | 1       |Noida     | 3333
Test4    | 2       |Chennai   | 5565
Test5    | 1       |Chennai   | 5565

需要所有客户行,同时具有noida和chennai地址
预期结果:

Test2    | 2       |Noida     | 3333
Test2    | 3       |Chennai   | 5565
Test4    | 1       |Noida     | 3333
Test4    | 2       |Chennai   | 5565
kognpnkq

kognpnkq1#

一个简单的方法是 exists . 只有两个地址:

select t.*
from t
where t.city in ('Noida', 'Chennai') and
      exists (select 1
              from t t2
              where t2.customer = t.customer and
                    t2.city in ('Noida', 'Chennai') and
                    t2.city <> t.city
             );
iszxjhcz

iszxjhcz2#

您可以使用windows函数

select * from
(select t.*, count(distinct city) over (partition by customer) as cnt
from your_Table t
where city in ('Noida','Chennai')
) where cnt = 2
bttbmeg0

bttbmeg03#

SELECT *
FROM your_table 
WHERE Customer IN (
  SELECT Customer 
  FROM your_table 
  WHERE City IN ('Noida', 'Chennai')
  GROUP BY Customer
  HAVING COUNT(DISTINCT City) = 2
)
zysjyyx4

zysjyyx44#

要获得想要的结果,您需要选择城市为“noida”或“chennai”、客户为“test2”或“test4”的所有数据:

SELECT *
  FROM TEST_DATA
  WHERE CITY IN ('Noida', 'Chennai') AND
        CUSTOMER IN ('Test2', 'Test4')
  ORDER BY Customer

db<>在这里摆弄

相关问题