在行中查找last not null值的列名

use*_*813 5 sql-server-2008

表是这样的

ID A1   A2   A3   A4   A5   A6   A7   A8   A9
1  YE  YE    YE  NULL  YE   YE   YE  NULL NULL
2  YE  YE    YE  NULL NULL NULL NULL NULL NULL
3  YE  YE    YE   YE   YE    YE   YE  YE  NULL

ID是主键.
我想在一行中获取最后一个非空值的列名,结果是这样的

ID LAST
1   A7
2   A3
3   A8

对此有何帮助?

小智 2

尽管我对此模式心存疑虑,但请考虑这个“反向优先级”条件:

select
  id,
  case
    -- first match terminates search
    when A9 is not null then 'A9'
    when A8 is not null then 'A8'
    when A7 is not null then 'A7'
    ..
    else null
  as lastNonNullColumn
from ..
Run Code Online (Sandbox Code Playgroud)

TSQL 中保证了求值的顺序(参见CASE),所以我们只是倒着走:)

按照指定的顺序计算每个 WHEN 子句的 Boolean_expression。

另外,也许可以使用UNPIVOT(或ROLLUP[?]或手册)。UNION也就是说,将固定的列名集转换为值,然后这是一个简单的查询..也就是说,如果表被规范化,这可以很容易地完成:-)

select
  id,
  max(colName) as lastNonNullColumn
from <<normalized_derived_table>>
where colValue is not null
group by id
Run Code Online (Sandbox Code Playgroud)