SQL - 创建一个包含基于月份的列和基于年份的行的自定义表

时间:2013-07-29 15:55:04

标签: mysql sql customcolumn

我正在尝试创建一个非常棒的自定义表来计算行数并组织它们,以便如果有三行日期为2013年1月,2014年3月为4,2014年10月为5,则表格将显示为:

     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2013 3   0   0   0   0   0   0   0   0   0   0   0
2014 0   0   4   0   0   0   0   0   0   5   0   0

1 个答案:

答案 0 :(得分:0)

我建议使用视图,而不是新表,当您的基础数据更改时,新表格不会不同步。

由于你没有提供太多的样本数据,我不得不假设一个结构,但你会想要这样的东西:

CREATE TABLE T (`Date` DATETIME);
INSERT T (`Date`)
VALUES 
    ('2013-01-01'), ('2013-01-02'), ('2013-01-03'), 
    ('2014-03-01'), ('2014-03-02'), ('2014-03-03'),
    ('2014-10-01'), ('2014-10-01'), ('2014-10-01'),
    ('2014-10-01'), ('2014-10-01');

CREATE VIEW V
AS
    SELECT  YEAR(`Date`) AS `Year`,
            COUNT(CASE WHEN MONTH(`Date`) = 1 THEN 1 END) AS `Jan`,
            COUNT(CASE WHEN MONTH(`Date`) = 2 THEN 1 END) AS `Feb`,
            COUNT(CASE WHEN MONTH(`Date`) = 3 THEN 1 END) AS `Mar`,
            COUNT(CASE WHEN MONTH(`Date`) = 4 THEN 1 END) AS `Apr`,
            COUNT(CASE WHEN MONTH(`Date`) = 5 THEN 1 END) AS `May`,
            COUNT(CASE WHEN MONTH(`Date`) = 6 THEN 1 END) AS `Jun`,
            COUNT(CASE WHEN MONTH(`Date`) = 7 THEN 1 END) AS `Jul`,
            COUNT(CASE WHEN MONTH(`Date`) = 8 THEN 1 END) AS `Aug`,
            COUNT(CASE WHEN MONTH(`Date`) = 9 THEN 1 END) AS `Sep`,
            COUNT(CASE WHEN MONTH(`Date`) = 10 THEN 1 END) AS `Oct`,
            COUNT(CASE WHEN MONTH(`Date`) = 11 THEN 1 END) AS `Nov`,
            COUNT(CASE WHEN MONTH(`Date`) = 12 THEN 1 END) AS `Dec`
    FROM    T
    GROUP BY YEAR(`Date`);

<强> Example on SQL Fiddle