tags:

views:

33

answers:

3

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

+3  A: 
SELECT `id` FROM `table`
WHERE `num` IN (4, 5, 7)
GROUP BY `id`
HAVING COUNT(*) = 3
zerkms
correct. exact answer.
Karthik
what if you get 4,4,4 in a single group?
Chris Bednarski
Changing COUNT(*) = 3 to COUNT(DISTINCT `num`) = 3 should fix that
Daniel Renshaw
@Chris: as always such tasks are solved over unique data. i bet this question is not an exception of this "rule".
zerkms
A: 

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
Chris Bednarski
+1  A: 

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 
Daniel Renshaw