0

我有一个列日期的表;它包含几个月的记录,但不是连续的。为了查看存在哪些月份(当前意味着特定月份中有 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 
4

1 回答 1

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)
于 2013-04-25T21:16:10.950 回答