表是这样的
身份证 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 NULL
其中 ID 是主键。
我想获取一行中最后一个非空值的列名,结果是这样的
身份证最后
1 A7
2 A3
3 A8
这有什么帮助吗?
最佳答案
尽管我对这个模式有疑虑,但请考虑这个“反向优先级”的条件:
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 ..
TSQL 中保证了求值顺序(请参阅 CASE ),所以我们只是向后推进 :)
Evaluates, in the order specified, Boolean_expression for each WHEN clause.
另外,也许
UNPIVOT
(或 ROLLUP
[?] 或手册 UNION
)可以使用。也就是说,将一组固定的列名转换为值,然后这是一个简单的查询 .. 也就是说,如果表被规范化,这可以很容易地完成:-)select
id,
max(colName) as lastNonNullColumn
from <<normalized_derived_table>>
where colValue is not null
group by id
关于sql-server-2008 - 查找一行中最后一个非空值的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11801348/