Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Two Where Clauses on same column

In SQL Server 2008, I have below Table Sample.

Name   Num
----------
John    20
John    30
Peter   10
Peter   20
Peter   30
Marry   20
Marry   30
Mike    10
Mike    20
Mike    30
Phil    10
Phil    30

I want records having Num = 10 and Num = 20. The query will return

Name   Num
----------
Peter   10
Peter   20
Mike    10
Mike    20

Many thanks.

like image 580
user219628 Avatar asked Feb 13 '26 16:02

user219628


1 Answers

You want something like this:

SELECT Name, Num
FROM tbl
WHERE Name IN (
    SELECT Name FROM tbl
    WHERE Num IN (10, 20)
    GROUP BY Name 
    HAVING COUNT(*) = 2 -- Must have all items in the set of 2
)
AND Num IN (10, 20) -- still need to restrict, since the set is not maximal

But there are other ways to skin the "set of items with all the following attributes" cat.

like image 174
Cade Roux Avatar answered Feb 15 '26 13:02

Cade Roux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!