我有一个列日期表;它包含几个月的记录,但不是连续的。 要查看哪些月份存在(当前意味着特定月份中有1个或更多记录),我试图进行概述。它应该是这样的:
2013 Jan Feb Mar - May Jun // etc
2012 Jan - - Apr May - // etc
我可以获得目前几个月的所有头几天,但我仍陷入如何转置。如果我这样做:
SELECT
IF (d = 1, month ,'-') AS Jan,
IF (d = 2, month ,'-') AS Feb,
IF (d = 3, month ,'-') AS Mar
FROM
(SELECT
MONTH(date) AS d,
DATE_FORMAT(date, '%Y-%m-01') AS month
FROM
table
GROUP BY
month
ORDER BY
month) m
GROUP BY YEAR(month)
如果给出结果:
Jan Feb Mar
- - Mar
- Feb -
虽然它应该给:
Jan Feb Mar
- - Mar
Jan Feb Mar
答案 0 :(得分:0)
这样可以在没有子查询的情况下执行此操作:
SELECT
MAX(CASE WHEN MONTH(date) = 1 THEN 'Jan' ELSE '-' END) AS Jan,
MAX(CASE WHEN MONTH(date) = 2 THEN 'Feb' ELSE '-' END) AS Feb,
MAX(CASE WHEN MONTH(date) = 3 THEN 'Mar' ELSE '-' END) AS Mar,
MAX(CASE WHEN MONTH(date) = 4 THEN 'Apr' ELSE '-' END) AS Apr,
MAX(CASE WHEN MONTH(date) = 5 THEN 'May' ELSE '-' END) AS May,
MAX(CASE WHEN MONTH(date) = 6 THEN 'Jun' ELSE '-' END) AS Jun,
... and so on through December
FROM table
GROUP BY YEAR(date)