MySql:从一个表转出

时间:2017-02-25 13:07:38

标签: mysql pivot

我有这个选择

SELECT concat(date_format(startLesson, '%H:%i'), ' - ', date_format(endLesson, '%H:%i')) AS 'CALENDAR', case when classroom = 'third_a' THEN (select concat(surname, '\r\n', about, '\r\n', tcode, '\r\n', book)) END AS 'THIRD_A', case when classroom = 'THIRD_B' THEN (select concat(surname, '\r\n', about, '\r\n', tcode, '\r\n', book)) END AS 'THIRD_B' FROM test_calendar WHERE date(startLesson) = '2017-02-24'

产生这个输出:

CALENDAR---------------->THIRD_A--------------->THIRD_B
08:00 - 09:00---------->PIPPO(bla)------------>NULL
09:00 - 10:00---------->PLUTO(bla)------------>NULL
09:00 - 10:00---------->NULL------------------->PAPERINO

我需要将数据显示为:

CALENDAR---------------->THIRD_A--------------->THIRD_B
08:00 - 09:00---------->PIPPO(bla)------------>NULL
09:00 - 10:00---------->PLUTO(bla)------------>PAPERINO

表结构是:

id (int, pk)
classRoom_id (int)
lesson_id (int)
startLesson datetime
endLesson datetime
about varchar
tcode varchar
book varchar
surname

任何提示?

提前谢谢!

1 个答案:

答案 0 :(得分:3)

您似乎需要group by

SELECT concat(date_format(startLesson,  '%H:%i'), ' - ',  
              date_format(endLesson, '%H:%i')) AS CALENDAR,
       group_concat(case when classroom = 'third_a' 
                         then concat(surname, '\r\n', about, '\r\n', tcode, '\r\n', book))
                    end) as THIRD_A,
       group_concat(case when classroom = 'THIRD_B'
                         then concat(surname, '\r\n', about, '\r\n', tcode, '\r\n', book))
                    end) as THIRD_B
FROM test_calendar
WHERE date(startLesson) = '2017-02-24'
GROUP BY Calendar;

注意:

  • 如果您想要每组一行,请使用group by
  • 不需要没有from子句的子选择。
  • 如果有多个匹配项,则使用group_concat()。对于您问题中的数据,max()可能没问题。
  • 通常不鼓励在列中嵌入新行字符。