2012-07-23 32 views
1

我有1 + 5列的表如下。如何從一組列中選擇非空值?

MEMBERID ==>表示Member_ID

值1 ==>表示值1

值2 ==>表示值2

值3 ==>表示值3

值4 ==>表示值4

Value5 ==>表示Value5

在任何給定時間只有一列不爲空(在Value1,Value2,Value3,Value4和Value5的集合中)。

我想運行一個查詢,其中我得到的結果爲Member_ID,其中值爲非5值的任何5值列的值。

如何在TSQL中做到這一點? 謝謝 史密斯

回答

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

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

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

變得挑剔,但不需要額外的函數調用。 coalesce(value1,value2,value3,value4,value5,) – Bill 2012-07-23 21:36:48

+0

@Bill Go圖,我不知道。修改。 – Bert 2012-07-23 21:37:47

+0

OOPS!所有的Value1到Value5都是不同的數據類型列。它們是布爾型,整型,日期時間。 – LaysomeSmith 2012-07-23 23:11:30

0

你可以嘗試一個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語句返回一個默認值,如果所有值都爲空的可能性。

+0

此外,在case語句中,如果Values1到5的數據類型具有不同類型,則可以將其轉換爲常用返回類型。 – 2015-03-19 10:14:51

相關問題