简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM