当前位置: 代码迷 >> Sql Server >> 关于COALESCE取值的有关问题
  详细解决方案

关于COALESCE取值的有关问题

热度:51   发布时间:2016-04-27 14:22:37.0
关于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 table1select 'A1', 'A2', null union allselect null, 'B2', 'B3' union allselect 'C1', null, null ;with t4 as(select row_number() over(partition by rn order by f desc) fn, t3.rn,t3.f,t3.cfrom(select rn,f,cfrom (select row_number() over(order by getdate()) rn, field1,field2,field3 from table1) t1unpivot(c for f in(field1,field2,field3)) t2) t3)select c value,f fieldfrom t4 where fn=1value  field----- --------A2     field2B3     field3C1     field1