Case语句如果全部为NULL或至少存在一个值

时间:2017-08-18 14:56:50

标签: sql-server tsql

我可能做错了,但这里有关于我思考的地方的详细信息。

我有一张桌子,我们称之为桌子:

Test     ID     Value
test_1   01     50
test_2   01     NULL
test_3   01     40/50
test_1   02     NULL
test_2   02     NULL

摘要

我只是想制作一个CASE表达式,如果所有测试值都为NULL则为“否”,如果至少有一个测试值的值为“是”,则为“否”。

期望输出:

ID   Case
01   Yes
02   No

当前查询:

SELECT
    ID
   ,CASE WHEN t.test IN ('test_1','test_2','test_3') IS NOT NULL
        THEN 'Yes'
        ELSE 'No'  END
FROM table t

错误

  

关键字“IS”附近的语法不正确。

1 个答案:

答案 0 :(得分:2)

使用聚合....

declare @table table (test varchar(6), id int, value varchar(24))
insert into @table
values
('test_1','01','50'),
('test_2','01',NULL),
('test_3','01','40/50'),
('test_1','02',NULL),
('test_2','02',NULL)

select
    t.id
    ,case when min(t.value) is null and max(t.value) is null then 'NO' else 'YES' end as [Case]
from
    @table t
group by
    t.id

实际上,你只需要检查一次。

select
    t.id
    ,case when max(t.value) is null then 'NO' else 'YES' end as [Case]
from
    @table t
group by
    t.id
相关问题