日期:2014-05-18  浏览次数:20764 次

关于COALESCE取值的问题
table1
======
field1 field2 field3
======
A1 A2 null
NULL B2 B3
C1 NULL NULL


取得第一个非空值
select COALESCE(field3,field2,field1) first_data from table

以上都没问题

问题是 我想知道 我取得的值对应的 字段名

比如 我取得了第一行倒过来第一个非空值是A2,我想知道他的字段名field2

这个要怎么写?

------解决方案--------------------
那就都用case when 去判断吧!
------解决方案--------------------
SQL code

create table table1
(field1 char(4), field2 char(4), field3 char(4))

insert into table1
select 'A1', 'A2', null union all
select null, 'B2', 'B3' union all
select 'C1', null, null 


;with t4 as
(select row_number() over(partition by rn order by f desc) fn, t3.rn,t3.f,t3.c
from
(select rn,f,c
from (select row_number() over(order by getdate()) rn, field1,field2,field3 from table1) t1
unpivot(c for f in(field1,field2,field3)) t2) t3
)
select c value,f field
from t4 where fn=1

value  field
----- --------
A2     field2
B3     field3
C1     field1