如何挑选一组列的非NULL值?(How to pick the non-NULL value fro

2019-10-17 02:09发布

我有1分+ 5列如下表。

MEMBERID ==>表示Member_ID

值1 ==>表示值1

值2 ==>表示值2

值3 ==>表示值3

VALUE4 ==>表示VALUE4

值5 ==>表示值5

只有一栏是不是在任何给定时间(在设定值1,值2,值3,值4和值5的)空。

我想运行一个查询在那里我得到的结果作为Member_ID,值,其中值是任何价值5列的非空值。

如何做到这一点在TSQL? 谢谢你,史密斯

Answer 1:

select memberID, coalesce(value1, value2, value3, value4, value5)
from myTable

如果可能性是存在的所有的值可能是零,您可能希望默认值。

select memberID, coalesce(value1, value2, value3, value4, value5, <default>)
from myTable


Answer 2:

你可以尝试一个case语句

select memberID,
       case
           when Value1 is not null then
               Value1
           when Value2 is not null then
               Value2  
           when Value3 is not null then
               Value3
           when Value4 is not null then
               Value4
           when CValue5 is not null then
               Value5
       end as [Value]
from myTable

也有添加一个“其他”的case语句返回一个默认值,如果所有值都为空的可能性。



文章来源: How to pick the non-NULL value from a set of columns?
标签: sql tsql