2016-07-22 47 views
2

在MSSQL中,想象我有以下數據的表...MSSQL - 返回列名和值,如果值不爲空

id name monday tuesday wednesday thursday friday 
1 mark null chores  null  gym  swim 
2 steve gym  null  class  hockey  null 
3 mike chores gym   null  null  null 

我想有一個SQL語句,將返回ID,名稱和日期列的值不爲空,例如...

id name day  value 
1  mark tuesday chores 
1  mark thursday gym 
1  mark friday  swim 
2  steve monday  gym 
2  steve wednesday class 
2  steve thursday hockey 
2  mike monday  chores 
2  mike tuesday gym 

謝謝。

+1

您應該創建表保存一週天,然後做人與人之間的關係 - 天 – Grommy

+0

SELECT * from yourtable where value is null –

回答

3

一種方法是union all,但我更喜歡outer apply

select t.id, t.name, dayname, value 
from t outer apply 
    (values ('monday', monday), 
      ('tuesday', tuesday), 
      ('wednesday', wednesday), 
      ('thursday', thursday), 
      ('friday', friday), 
      ('saturday', saturday), 
      ('sunday', sunday) 
    ) v(dayname, value) 
where value is not null; 
+0

我先試過這個解決方案,它的工作原理與我想要的完全一樣。謝謝。 – MaxAx

2

嘗試

select * from yourTable 
unpivot 
(
day1 for value in (monday, tuesday, wednesday, thursday,friday) 
) upt