在使用COALESCE功能后,有人可以帮助我使用以下查询更新结果列名称EG:A或B或C吗?
示例:
表:
A - null,
B - null,
C - 5
select COALESCE(A,B,C) As [COL1], [COL2]
from TABLE
在这种情况下,[Col2]应将列名显示为' C'
结果:
[COl1] = 5
[Col2] = C (Displays the Column Name)
谢谢, Kavin
答案 0 :(得分:1)
一种方法使用case
:
select coalesce(A, B, C) As [COL1],
(case when A is not null then 'A'
when B is not null then 'B'
when C is not null then 'C'
end) as [COL2]
from TABLE;
如果你想要花哨,你可以使用APPLY
:
select v.val, v.col
from t outer apply
(select top (1) v.*
from (values (t.A, 'A', 1), (t.B, 'B', 2), (t.C, 'C', 3)
) v(val, col, ord)
where val is not null
order by ord
) tt;