我想在sql请求帮助,我有一个表格
ID | Indicator1 | Indicator2 | Indicator3 | Indicator4
1 | 1 | 0 | 0 | 0
2 | 0 | 1 | 1 | 0
3 | 1 | 1 | 0 | 0
4 | 0 | 0 | 0 | 0
我想让它看起来像这样
ID | Indicators
1 | Indicator1
2 | Indicator2
2 | Indicator3
3 | Indicator1
3 | Indicator2
4 | NULL
有什么建议吗?谢谢
答案 0 :(得分:0)
使用UNPIVOT。
SELECT p.Id,
p.Indicators,
p.IndicatorsValue
FROM TableName
UNPIVOT
(
IndicatorsValue FOR Indicators IN (Indicator1,Indicator2,Indicator3,Indicator4)
)AS p
答案 1 :(得分:0)
select b.* from #temp a left join (
SELECT p.Id,
p.Indicators
FROM #temp
UNPIVOT
(
IndicatorsValue FOR Indicators IN (Indicator1,Indicator2,Indicator3,Indicator4)
)AS p
where p.IndicatorsValue <>0)b on a.id=b.id
答案 2 :(得分:0)
使用UNPIVOT并添加过滤器以删除不必要的列:
SELECT DISTINCT ID, Indicators
FROM #Indicator
UNPIVOT (IndicatorsValue
FOR Indicators IN (Indicator1,Indicator2,Indicator3,Indicator4)) AS up
WHERE up.IndicatorsValue <> 0