我有一张表格,如屏幕截图所示。预期的结果以彩色突出显示。
我有6列,它们是从1到6的过程的各个阶段。 假设用户跳过了一个过程,那么这些值将为空,但是下一阶段会有一些值(蓝色)。如果在随后的阶段中没有值,则它们为空(绿色),我想区分绿色和蓝色值。 我的意思是,如果列值是空的并且具有下一个阶段(后续列中有值),则该列值为b。 如果列值为空且没有下一个阶段(后续列中没有值),则列值为g
答案 0 :(得分:2)
为此,您将需要一个冗长的CASE表达式。您可以通过使用COALESCE
和IIF
来将其缩短一点,它们都将转换为CASE表达式:
SELECT
COALESCE(col1, IIF(col2 IS NULL AND col3 IS NULL AND col4 IS NULL AND col5 IS NULL AND col6 IS NULL, 'g', 'b')) AS col1,
COALESCE(col2, IIF( col3 IS NULL AND col4 IS NULL AND col5 IS NULL AND col6 IS NULL, 'g', 'b')) AS col2,
COALESCE(col3, IIF( col4 IS NULL AND col5 IS NULL AND col6 IS NULL, 'g', 'b')) AS col3,
COALESCE(col4, IIF( col5 IS NULL AND col6 IS NULL, 'g', 'b')) AS col4,
COALESCE(col5, IIF( col6 IS NULL, 'g', 'b')) AS col5,
COALESCE(col6, 'g') AS col6
答案 1 :(得分:1)
好吧,您可以使用大写的case表达式:
select (case when col1 is null and (col2 is not null or col3 is not null or col4 is not null or col5 is not null or col6 is not null)
then 'b'
when col1 is null
then 'g'
else col1
end) as col1,
(case when col2 is null and (col1 is not null or col3 is not null or col4 is not null or col5 is not null or col6 is not null)
then 'b'
when col2 is null
then 'g'
else col2
end) as col2,
. . .
from t;