Set*_*man 3 sql t-sql sql-server pivot
您能否在透视查询中透视两列。
假设我有以下数据...
CREATE TABLE JudgeScores
(PerformanceID int,
JudgeID int,
Criteria varchar(10),
StrengthScore decimal(9,4),
StyleScore decimal(9,4))
--first team performance
--judge1
INSERT INTO JudgeScores (1, 1, "Stunts", 4.2, 1.1)
INSERT INTO JudgeScores (1, 1, "Jumps", 3.9, 0.8)
INSERT INTO JudgeScores (1, 1, "Tumbling", 4.5, 1.0)
INSERT INTO JudgeScores (1, 1, "Choreography", 4.2, 1.5)
--judge2
INSERT INTO JudgeScores (1, 2, "Stunts", 4.1, 1.1)
INSERT INTO JudgeScores (1, 2, "Jumps", 4.0, 0.9)
INSERT INTO JudgeScores (1, 2, "Tumbling", 4.4, 1.1)
INSERT INTO JudgeScores (1, 2, "Choreography", 4.2, 1.6)
--judge3
INSERT INTO JudgeScores (1, 3, "Stunts", 3.8, 1.2)
INSERT INTO JudgeScores (1, 3, "Jumps", 4.2, 0.7)
INSERT INTO JudgeScores (1, 3, "Tumbling", 4.3, 1.2)
INSERT INTO JudgeScores (1, 3, "Choreography", 4.1, 1.3)
--second team performance
--judge1
INSERT INTO JudgeScores (2, 1, "Stunts", 4.3, 1.3)
INSERT INTO JudgeScores (2, 1, "Jumps", 4.0, 0.9)
INSERT INTO JudgeScores (2, 1, "Tumbling", 4.6, 1.1)
INSERT INTO JudgeScores (2, 1, "Choreography", 4.0, 1.0)
--judge2
INSERT INTO JudgeScores (2, 2, "Stunts", 4.1, 1.1)
INSERT INTO JudgeScores (2, 2, "Jumps", 4.0, 0.9)
INSERT INTO JudgeScores (2, 2, "Tumbling", 4.5, 1.2)
INSERT INTO JudgeScores (2, 2, "Choreography", 4.2, 1.6)
--judge3
INSERT INTO JudgeScores (2, 3, "Stunts", 4.1, 1.1)
INSERT INTO JudgeScores (2, 3, "Jumps", 4.5, 0.9)
INSERT INTO JudgeScores (2, 3, "Tumbling", 4.4, 1.2)
INSERT INTO JudgeScores (2, 3, "Choreography", 4.2, 1.6)
Run Code Online (Sandbox Code Playgroud)
我想选择数据,以便它将数据按如下所示旋转
PerformanceID, JudgeID, StuntsStrength, StuntsStyle, JumpsStrength, JumpsStyle, TumbleStrength, TumbleStyle, ChorStrength, ChorStyle
1 1 4.2, 1.1, 3.9, 0.8, 4.5, 1.0, 4.2, 1.5
1 2 4.1, 1.1, 4.0, 0.9, 4.4, 1.1, 4.2, 1.6
...
2 1 4.3, 1.3, 4.0, 0.9, 4.6, 1.1, 4.0, 1.0
2 2 4.1, 1.1, 4.0, 0.9, 4.5, 1.2, 4.2, 1.6
2 3 ...
Run Code Online (Sandbox Code Playgroud)
可以使用数据透视查询完成此操作。如果不是,最好的方法是什么?
IMO比枢轴等效项更具可读性。
使其简单易维护:
select PerformanceId,
JudgeId,
[StuntsStrength] = avg(case when Criteria = 'Stunts' then StrengthScore else null end),
[StuntsStyle] = avg(case when Criteria = 'Stunts' then StyleScore else null end),
[JumpsStrength] = avg(case when Criteria = 'Jumps' then StrengthScore else null end),
[JumpsStyle] = avg(case when Criteria = 'Jumps' then StyleScore else null end),
[TumbleStrength] = avg(case when Criteria = 'Tumbling' then StrengthScore else null end),
[TumbleStyle] = avg(case when Criteria = 'Tumbling' then StyleScore else null end),
[ChorStrength] = avg(case when Criteria = 'Choreography' then StrengthScore else null end),
[ChorStyle] = avg(case when Criteria = 'Choreography' then StyleScore else null end)
from dbo.JudgeScores
group
by PerformanceId, JudgeId;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1227 次 |
| 最近记录: |