T-SQL Two Where子句在同一列上

时间:2010-12-07 22:48:37

标签: sql-server tsql where-clause

在SQL Server 2008中,我有下表示例。

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

我想要Num = 10和Num = 20的记录。查询将返回

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

非常感谢。

4 个答案:

答案 0 :(得分:6)

你想要这样的东西:

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

但是还有其他一些方法可以将“具有以下所有属性的项目集”设置为“猫”。

答案 1 :(得分:1)

其中任何一个都会产生你想要的输出:

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

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

编辑:抱歉,这似乎不是你想要的。我相信这会奏效,但不是很优雅:

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

可能有更好的解决方案。对不起有误。

答案 2 :(得分:1)

你可以试试这个

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)
        )

答案 3 :(得分:-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