我正在写一个案例陈述,我需要检查列并分配一个值。但如果一行有资格获得多个案例呢?例如,在下表中,我想在COLA和/或COLB为空时分配一个桶;所以在第一种情况下两者都是NULL,所以当COLA和COLB为空时,如何告诉SQL case语句分配“Both are NULL”。当COLA或COLB为空时,我可以轻松分配。在我的工作中,我正在检查8列,所以我需要找到每个组合和正确的案例吗?必须有一个简单的方法。
**RowNumber COLA COLB Case**
1 Null Null **Both are NULL**
2 Null B A is null
3 A Null B is null
4 AA BB NULL
5 CC Null B is null
答案 0 :(得分:7)
鉴于您有8列,您可能需要执行以下操作:
WITH t AS (
SELECT
CASE WHEN (colA IS NULL AND colB IS NULL AND colC IS NULL AND colD IS NULL AND
colE IS NULL AND colF IS NULL AND colG IS NULL AND colH IS NULL) THEN 'ALL' ELSE '' END [ALL],
CASE WHEN colA IS NULL THEN 'A' ELSE '' END [A],
CASE WHEN colB IS NULL THEN 'B' ELSE '' END [B],
CASE WHEN colC IS NULL THEN 'C' ELSE '' END [C],
CASE WHEN colD IS NULL THEN 'D' ELSE '' END [D],
CASE WHEN colE IS NULL THEN 'E' ELSE '' END [E],
CASE WHEN colF IS NULL THEN 'F' ELSE '' END [F],
CASE WHEN colG IS NULL THEN 'G' ELSE '' END [G],
CASE WHEN colH IS NULL THEN 'H' ELSE '' END [H]
FROM
<TABLENAME>)
SELECT
CASE WHEN [ALL] = 'ALL' THEN 'ALL are NULL'
ELSE [ALL] + ',' + A + ',' + B + ',' + C + ',' + D + ','
+ E + ',' + F + ',' + G + ',' + H + ' are NULL'
END
FROM T
在最终的select语句中,您可以进行进一步的更改以根据需要显示结果。