我在SQL server中有一个表(T1):
id subject student1 student2 student3 score1 score2 score3
1 Maths Peter Leo John 11 12 13
2 Phy Mary May Leo 21 22 23
是否可以使用查询来产生以下结果:
id subject name score
1 Maths Peter 11
1 Maths Leo 12
1 Maths John 13
2 Phy Mary 21
2 Phy May 22
2 Phy Leo 23
答案 0 :(得分:5)
虽然这是一个univot查询,但实际上我发现用显式逻辑更容易做到这一点:
select t1.id, t1.subject,
(case when n.n = 1 then student1
when n.n = 2 then student2
when n.n = 3 then student3
end) as student,
(case when n.n = 1 then score1
when n.n = 2 then score2
when n.n = 3 then score3
end) as score
from t1 cross join
(select 1 as n union all select 2 union all select 3) n;
这应该具有与unpivot
相当的性能。并且,它应该具有比三个union all
操作更好的性能(因为这需要扫描表三次)。
答案 1 :(得分:2)
尝试此查询
SELECT a.id, a.subject, b.*
FROM dbo.Table1 a
CROSS APPLY (
SELECT 1, a.student1, a.score1
UNION ALL
SELECT 2, a.student2, a.score2
UNION ALL
SELECT 3, a.student3, a.score3
) b(num, student, score)
答案 2 :(得分:1)
假设该表被称为类,您可以将它与自身联合起来:
(SELECT student1 as student, subject from Classes)
UNION
(SELECT student2 as student, subject from Classes)
UNION
(SELECT student3 as student, subject from Classes)