1

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

如果某事是“完整的”,则分组 checkid 的所有 statusid 值都是 1 或 10 或 40。Statusid 值不是连续的(有许多 statusid 值,这只是一个摘录)。有人可以展示我如何在案例子查询中执行 In 子句,或者只是一种更简洁的方式来编写它吗?

预期结果集

    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

错误:

在预期条件的上下文中指定的非布尔类型的表达式,靠近“Where”。

谢谢。

4

1 回答 1

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(expression) 聚合不计数的事实NULL(aisde: 尽管COUNT(*)会)。对于所有条目都是状态 1、10 或 40 的组,嵌套CASE将为该组中的每一行返回 1,等于该组的 COUNT(*)。如果组中的一个成员不是状态 1、10 或 40,则嵌套CASE将返回NULL,不会被 计数COUNT

于 2012-09-19T05:09:02.533 回答