[英]Generate columns from distinct values
I have a three column table which lists every person, every event they may have attended, and what percentage of the time they were there. 我有一个三列的表格,其中列出了每个人,他们可能参加的每个活动以及他们在那儿的时间百分比。 I would really like to display this on one page with the person names on the side and the event names across the top. 我真的很想在一页上显示此内容,并在侧面显示人员名称,在顶部显示事件名称。
Here' an example of what I have: 这是我所拥有的一个例子:
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
And here's what I would like to show. 这是我想展示的。
NAME ROCK CLIMBING CANOEING FENCING ARCHERY
Smith 50 - - -
Allen 75 87 - 100
Moore 100 100 98 34
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
reference : http://msdn.microsoft.com/en-us/library/ms177410.aspx 参考: http : //msdn.microsoft.com/zh-cn/library/ms177410.aspx
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)
Note: the first part is only for testing. 注意:第一部分仅用于测试。 Not very flexible approach but might work for you. 不是很灵活的方法,但可能对您有用。
Result: 结果:
Name Rock Climbing Canoeing Fencing Archery
Smith 50 - - -
Allen 78 87 - 100
Moore 100 100 98 34
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.