TSQL - 选择具有相同列A但不同列B的行

时间:2017-10-26 09:48:05

标签: sql sql-server database tsql

我正在尝试查找没有ID = 1的行(名称)。例如,如果我的表看起来像这样:

Name     ID        
--------------
A      1
A      0
B      1
B      0
C      0 
D      2
D      0

此查询的答案是:

Name
-----
C
D

你有什么想法吗?

4 个答案:

答案 0 :(得分:3)

SELECT Name
FROM myTable
GROUP BY Name
HAVING SUM(CASE WHEN ID = 1 THEN 1 ELSE 0 END) = 0

答案 1 :(得分:1)

这是一种方法:

SELECT DISTINCT Name
FROM Table t0
WHERE NOT EXISTS
(
    SELECT 1
    FROM Table t1
    WHERE t0.Name = t1.Name
    AND t1.Id = 1
)

答案 2 :(得分:0)

Select Distinct name 
From myTable
Where name not in (Select name From myTable Where id= 1) 

答案 3 :(得分:0)

尝试此查询:

SELECT DISTINCT(name)
FROM tbl t1 
WHERE 
NOT EXISTS (SELECT name FROM tbl t2 WHERE ID=1 AND t1.name=t2.name)