一个有趣的棘手的过滤器(不知道如何在标题中描述它)

时间:2016-06-01 18:04:27

标签: sql sql-server tsql

我的表是这样的:

Item   Subitem    Progress  
1      101        Complete  
1      102        Pending
1      103        Pending
2      201        Complete
2      202        Complete

我想选择子项全部完整的项目 - 在这种情况下,项目#2。知道怎么做吗? 谢谢!

2 个答案:

答案 0 :(得分:6)

有很多方法:

select Item from T group by Item
having min(Progress) = max(Progress) and max(Progress) = 'Complete'

having count(case when Progress = 'Complete' then 1 end) = count(*)

having count(case when Progress = 'Complete' then null else 1 end) = 0 /* handles nulls */

select distinct Item from T t
where 'Complete' = all (select Progress from T t2 where t2.Item = t.Item)

答案 1 :(得分:2)

因此,您基本上希望所有没有任何Subitems处于待处理状态的项目

假设您显示的表是SubItems表,并且还有另一个Items表...

SELECT *
FROM Items
WHERE ITEMID NOT IN (SELECT ITEMID 
                     FROM SubItems 
                     WHERE Progress != 'Complete')