2016-07-22 81 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