T-SQL:将列值移动到行值
我想让一个case语句(或您建议的语句)生成多个结果,这些多个结果将反映在输出中。然而,使用底部的示例,我没有得到期望的结果。提前谢谢 目前:T-SQL:将列值移动到行值,sql,tsql,Sql,Tsql,我想让一个case语句(或您建议的语句)生成多个结果,这些多个结果将反映在输出中。然而,使用底部的示例,我没有得到期望的结果。提前谢谢 目前: ID Phase Total Hours Team1 Team2 Team3 1 Test 50 25 10 15 2 QA 60 20 20 20 3 Impl 40 0 20 20 寻找: ID Phase Total Hours
ID Phase Total Hours Team1 Team2 Team3
1 Test 50 25 10 15
2 QA 60 20 20 20
3 Impl 40 0 20 20
寻找:
ID Phase Total Hours Team Name Team Hour
1 Test 50 Team 1 25
1 Test 50 Team 2 10
1 Test 50 Team 3 15
2 QA 60 Team 1 20
2 QA 60 Team 2 20
2 QA 60 Team 3 20
3 Impl 40 Team 2 20
3 Impl 40 Team 3 20
Select ID, Phase, Total Hours,
case
When Team1 is not null and Team1 is >0 then 'Team1'
When Team2 is not null and Team2 is >0 then 'Team2'
When Team3 is not null and Team3 is >0 then 'Team3'
end as 'Team Name',
case
When Team1.Hrs is not null and Team1.Hrs is >0 then Team1.Hrs
When Team2.Hrs is not null and Team2.Hrs is >0 then Team2.Hrs
When Team3.Hrs is not null and Team3.Hrs is >0 then Team3.Hrs
end as 'Team Hours'
From DB.DBNAME
丑陋,但是
SELECT ID, Phase, [Total Hours], 'Team1' AS Team, Team1 AS [Team Hours]
FROM DB.DBNAME
UNION
SELECT ID, Phase, [Total Hours], 'Team2' AS Team, Team2 AS [Team Hours]
FROM DB.DBNAME
UNION
SELECT ID, Phase, [Total Hours], 'Team3' AS Team, Team3 AS [Team Hours]
FROM DB.DBNAME
您需要这样返回查询,并且无法执行常规查询并在客户端重新排列数据的任何原因?请使用UNPIVOT。例如:
;WITH t AS(
SELECT * FROM (VALUES(1,'Test',50,25,10,15),(2,'QA',60,20,20,20),(3,'Impl',40,0,20,20)
)x(ID, Phase, [Total Hours], Team1, Team2, Team3)
)
SELECT ID,Phase, [Total Hours], [Team Name], [Team Hour]
FROM t
UNPIVOT
([Team Hour] FOR [Team Name] IN (Team1, Team2, Team3)) AS unpvt
WHERE [Team Hour] > 0
示例查询生成什么?创建一个存储过程来执行一对多查询。谢谢你的帮助。