1

I am trying to make an awesome custom table which counts the amount of rows and organises them so that if there are three rows with a date in January 2013, four in March 2014 and five in October 2014 the table would show up as:

     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
4

1 回答 1

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`);

SQL Fiddle 示例

于 2013-07-29T16:05:26.347 回答