开发者

How to check group for containing certain elements in SQL?

开发者 https://www.devze.com 2022-12-28 19:27 出处:网络
I have a simple table: id num 1 7 1 5 1 4 2 5 2 4 2 7 3 4 3 7开发者_开发百科 How to select ids having num 5 as well as 7 and 4

I have a simple table:

id num

1 7
1 5
1 4

2 5
2 4
2 7

3 4
3 7开发者_开发百科

How to select ids having num 5 as well as 7 and 4

For this example ids: 1, 2


SELECT `id` FROM `table`
WHERE `num` IN (4, 5, 7)
GROUP BY `id`
HAVING COUNT(*) = 3


This is a very slightly amended version of zerkms' answer:

SELECT `id` FROM `table` 
WHERE `num` IN (4, 5, 7) 
GROUP BY `id` 
HAVING COUNT(DISTINCT `num`) = 3 


How about

;WITH T AS
(
    SELECT ID, NUM, COUNT(*) OVER(PARTITION BY ID) AS ROWNO,
           SUM(NUM) OVER(PARTITION BY ID) AS SUMNUM
    FROM TABLE
)
SELECT ID, NUM
FROM T
WHERE ROWNO = 3 AND SUMNUM = 16
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号