子查询帮助中的SQL Server案例计数?

时间:2012-09-18 20:50:10

标签: sql-server-2008 aggregate-functions case

我的桌子中有很多种状态。某些值意味着表中的工作是“完整的”。

如果某些内容“完整”,则分组checkid的所有statusid值都是 Statusid值不连续(有许多statusid值,这只是一个提取)。有人可以展示我如何在一个案例子查询中做一个In Clause,或者只是一个更简洁的方式来编写它?

预期结果集

    checkid    iscomplete
    3           0
    4           1
    5           0
    6           0

4完成,因为只有一行,它有一个“10”。 3是不完整的,因为其中一个值是“1”而其他值是“2”。 5未完成,因为它只有“30”值。 6是不完整的,因为它有一个“40”但它也有一个“30”。

DML:

create table #test1 ( test1id int identity primary key , checkid int  , statusid int )
insert into #test1 ( checkid , statusid ) values (3 , 1)
insert into #test1 ( checkid , statusid ) values (3 , 2)
insert into #test1 ( checkid , statusid ) values (3 , 2)
insert into #test1 ( checkid , statusid ) values (4 , 10)
insert into #test1 ( checkid , statusid ) values (5 , 30)
insert into #test1 ( checkid , statusid ) values (5 , 30)
insert into #test1 ( checkid , statusid ) values (6 , 30)
insert into #test1 ( checkid , statusid ) values (6 , 40)

select  checkid 
, iscomplete =  ( case when count(*) Where #test1.statusid In ( 1,10,40) Then 1 )
from #test1
group by checkid

错误:

  

在上下文中指定的非布尔类型的表达式   条件是预期的,靠近'哪里'。

感谢。

1 个答案:

答案 0 :(得分:2)

编写满足要求的查询的一种方法是:

SELECT
    t.checkid,
    CASE 
        WHEN COUNT_BIG(*) = COUNT
            (
            CASE 
                WHEN t.statusid IN (1,10,40)
                THEN 1 
                ELSE NULL 
            END
            ) 
        THEN 1 
        ELSE 0 
    END
FROM #test1 AS t
GROUP BY
    t.checkid
ORDER BY
    t.checkid;

这利用了COUNT(表达式)聚合不计算NULL的事实(aisde:尽管COUNT(*)会)。对于所有条目都是状态1,10或40的组,嵌套的CASE将为该组中的每一行返回1,等于该组的COUNT(*)。如果该组中的一个成员不是状态1,10或40,则嵌套的CASE将返回NULLCOUNT将不会计入该值{。}}。