T-SQL Two Where Clauses on One Column

In SQL Server 2008, I have the table below.

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 need entries with Num = 10 and Num = 20. The request will return

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

Many thanks.

+3
source share
4 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 hide the "set of elements with all the following attributes" cat.

+6
source

Any of them will give the desired result:

SELECT * FROM Sample WHERE Num IN (10, 20)

or

SELECT * FROM Sample WHERE Num = 10 OR Num = 20

EDIT : Sorry, this doesn't seem to be what you wanted. I believe this will work, but it is not very elegant:

SELECT * FROM Sample
WHERE Name IN (SELECT Name FROM Sample WHERE Num = 10)
  AND Name IN (SELECT Name FROM Sample WHERE Num = 20)

Perhaps the best solution. Sorry for misunderstanding.

+1
source

SELECT Name, Num
FROM MyTableSample s
WHERE Num in (10, 20)
    AND EXISTS
        (
        SELECT Name
        FROM MyTableSample s2
        WHERE s.name = s2.Name
            AND s.Num <> s2.Num
            AND s2.Num in (10, 20)
        )
+1

SELECT *
  FROM    (SELECT Name, Num FROM Sample WHERE Num = 10) A,
                    (SELECT Name, Num FROM Sample WHERE Num = 20) B
where A.nAME = B.nAME       
-1

Source: https://habr.com/ru/post/1779072/


All Articles