MySQL获取日/月表/矩阵?

时间:2017-01-11 06:31:11

标签: mysql pivot-table

使用简单的日期和值表:

+------------+-------+
| date       | count |
+------------+-------+
| 2015-01-01 | 5     |
| 2015-01-02 | 2     |
| 2015-07-02 | 20    |

我如何获得所有月份的矩阵作为列,将天数作为行,使用值,使用单个MySQL查询可能使用子选择和连接?

+-----+----------+----------+---------
| Day | January  | February | March...
+-----+----------+----------+---------
| 1   | 5        | 8        | 12
| 2   | 2        | 9        | 5
| 3   | 5        | 12       | 6

这是否可行,而不使用PHP或任何其他脚本工具?

这将用于显示几个月的趋势和峰值。

2 个答案:

答案 0 :(得分:3)

你本质上拥有的是一个支点,你可以用条件总和(即包含CASE的SUM)来完成这个,按天数分组以得到各行:

select DAY(date) as Day,
       sum(case when MONTH(date) = 1 then count else 0 end) as January,
       sum(case when MONTH(date) = 2 then count else 0 end) as February,
       --...
       sum(case when MONTH(date) = 12 then count else 0 end) as December
from myTable
group by DAY(date)

答案 1 :(得分:0)

如果你只想要2015年的矩阵,你可以进行数据透视查询:

SELECT DATE_FORMAT(date, '%d') AS Day,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 1  THEN count END) AS January,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 2  THEN count END) AS February,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 3  THEN count END) AS March,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 4  THEN count END) AS April,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 5  THEN count END) AS May,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 6  THEN count END) AS June,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 7  THEN count END) AS July,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 8  THEN count END) AS August,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 9  THEN count END) AS September,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 10 THEN count END) AS October,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 11 THEN count END) AS November,
       MAX(CASE WHEN DATE_FORMAT(date, '%m') = 12 THEN count END) AS December
FROM yourTable
WHERE DATE_FORMAT(date, '%Y') = '2015'
GROUP BY DATE_FORMAT(col, '%d')