MSSQL - 如果value不为NULL,则返回列名和值

时间:2016-07-22 12:35:32

标签: sql sql-server

在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语句,它会返回值为非null的id,name和day列,例如......

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

谢谢。

2 个答案:

答案 0 :(得分:3)

一种方法是describe adgregator.adgregator ,但我更喜欢union all

outer apply

答案 1 :(得分:2)

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