我有一个三列表,其中列出了每个人,他们可能参加过的每个活动,以及他们在那里的时间百分比。我真的想在一个页面上显示这个,旁边是人名,顶部是事件名。
这是'我拥有的一个例子:
NAME EVENT %ATTENDANCE
Smith Rock Climbing 50
Allen Rock Climbing 78
Moore Rock Climbing 100
Moore Canoeing 100
Moore Fencing 98
Moore Archery 34
Allen Archery 100
Allen Canoeing 87
这就是我想要展示的内容。
NAME ROCK CLIMBING CANOEING FENCING ARCHERY
Smith 50 - - -
Allen 75 87 - 100
Moore 100 100 98 34
答案 0 :(得分:3)
select Name, [Rock Climbing],[Canoeing],[Fencing],[Archery]
from
(select * from YourTable) p
pivot
(
SUM(Attendance)
for Event in ( [Rock Climbing], [Canoeing],[Fencing],[Archery] )
)
as pvt
答案 1 :(得分:1)
WITH tAttendance (Name, Event, Attendance)
AS
(
SELECT 'Smith', 'Rock Climbing', 50 UNION ALL
SELECT 'Allen', 'Rock Climbing', 78 UNION ALL
SELECT 'Moore', 'Rock Climbing', 100 UNION ALL
SELECT 'Moore', 'Canoeing', 100 UNION ALL
SELECT 'Moore', 'Fencing', 98 UNION ALL
SELECT 'Moore', 'Archery', 34 UNION ALL
SELECT 'Allen', 'Archery', 100 UNION ALL
SELECT 'Allen', 'Canoeing', 87
)
SELECT Name
,(SELECT COALESCE(CAST(SUM(Attendance)AS varchar),'-')FROM tAttendance t2 WHERE t1.Name=t2.Name AND Event='Rock Climbing')AS [Rock Climbing]
,(SELECT COALESCE(CAST(SUM(Attendance)AS varchar),'-')FROM tAttendance t2 WHERE t1.Name=t2.Name AND Event='Canoeing')AS Canoeing
,(SELECT COALESCE(CAST(SUM(Attendance)AS varchar),'-')FROM tAttendance t2 WHERE t1.Name=t2.Name AND Event='Fencing')AS Fencing
,(SELECT COALESCE(CAST(SUM(Attendance)AS varchar),'-')FROM tAttendance t2 WHERE t1.Name=t2.Name AND Event='Archery')AS Archery
FROM tAttendance t1
GROUP BY Name
Order By SUM(Attendance)
注意:第一部分仅用于测试。不是很灵活的方法,但可能适合你。
结果:
Name Rock Climbing Canoeing Fencing Archery
Smith 50 - - -
Allen 78 87 - 100
Moore 100 100 98 34