如何在一列中打印多行数据?

时间:2014-12-02 13:22:32

标签: mysql sql select group-by pivot-table

我有两个mysql表如下?

TimeSchedule 

subID | date  | venue  | timeslot 

1     |  8-12 |  ABC   |   10 - 12

2     |  8-12 |  ABC   |   2 - 4 

subject

subID | name 

1     | Games
2     | Music

我想将这两个表数据显示如下?

Date | 10 - 12 | 2 - 4 |Venue

8-12 | Game    | Music | ABC

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t.date, 
       MAX(CASE WHEN t.timeslot = '10 - 12' THEN s.name ELSE '' END) AS `10 - 12`,  
       MAX(CASE WHEN t.timeslot = '2 - 4' THEN s.name ELSE '' END) AS `2 - 4`,  
       t.venue  
FROM TimeSchedule t
INNER JOIN `subject` s ON t.subID = s.subID  
GROUP BY t.date;