采取下表示例:
Name | List | FlagByList
---------------------------
A | 1 | Y
A | 2 | Y
B | 1 | Y
B | 2 | N
C | - | -
C | - | -
我想返回所有列表中包含“Y”的名称和任何列表中不存在的名称。
答案 0 :(得分:1)
简单的聚合查询可以做到这一点。
SELECT Name
FROM Table
GROUP BY Name
HAVING COUNT(1) = COUNT(CASE FlagByList WHEN 'Y' THEN 1 END) --counts all rows with Y as Value
OR COUNT(1) = COUNT(CASE WHEN FlagByList IS NULL THEN 1 END); --counts all rows with NULL as value
答案 1 :(得分:1)
使用解码
select name from example
group by Name
having sum(decode( FlagByList, 'Y',1, 0)) = count(*)
OR sum(decode(List, NULL, 0, 1)) = count(*)
答案 2 :(得分:-1)
请使用以下代码。它与SQL Server 2012一起工作正常。
DECLARE @Table TABLE (Name char(2),List char(2) , FlagByList char(2))
INSERT @Table
(Name,List,FlagByList)
VALUES
('A','1','Y'),
('A','2','Y'),
('B','1','Y'),
('B','2','N'),
('C','-','-'),
('C','-','-')
SELECT DISTINCT(Name) FROM @Table WHERE FlagByList ='Y'
UNION
SELECT DISTINCT(Name) FROM @Table WHERE FlagByList ='-'
EXCEPT
SELECT DISTINCT(Name) FROM @Table WHERE FlagByList ='N'