仅在* all *值不符合特定条件的情况下选择SQL中的行

时间:2014-08-04 15:13:02

标签: sql tsql group-by

在MS SQL中给出一个非常简单的表:

User ID | Status
----------------
1         False
2         True
2         False
3         False
3         False

我无法理解如何仅选择的任何行Status分配给True的用户。

结果将返回用户ID 1和3。

我觉得它需要的不仅仅是一个直接的WHERE选择器,并且一直在试验GROUP BY和COUNT而没有成功。

4 个答案:

答案 0 :(得分:7)

您可以使用带有GROUP BY子句的HAVING来获取结果。在HAVING中,您可以使用带有聚合的CASE表达式来过滤掉Status = 'True'的所有行:

select [user id]
from table1
group by [user id]
having sum(case when status = 'true' then 1 else 0 end) < 1;

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

尝试这种方式:

select distinct userid  
from yourtable
where userid not in (select userid 
                     from yourtable 
                     where status = 'True')

答案 2 :(得分:0)

这应该有效。请尝试

DECLARE @table TABLE (UserID INT,
                  Status VARCHAR(10))
INSERT INTO @table
VALUES
('1', 'False'),
('2', 'True'),
('2', 'False'),
('3', 'False'),
('3', 'False')

SELECT DISTINCT UserID,
             Status
FROM @table AS t1
WHERE EXISTS (SELECT 1
            FROM @table AS t2
            WHERE t1.UserID = t2.UserID
            GROUP BY UserID
            HAVING SUM(CASE
                       WHEN Status = 'True' THEN 1
                       ELSE 0
                    END ) = 0)

答案 3 :(得分:0)

select t1.[user id]
  from table1 t1
  left join table1 t2
    on t2.[user id] = t2.[user id] 
   and t2.[Status] = 'true'
 where t2.[user id] is null 
 group by t1.[user id]


select distinct [user id]
  from table1 
except 
select [user id]
  from table1 
 where [Status] = 'true'