【问题标题】:MySQL, how to do a sum by product and by monthMySQL,如何按产品和按月计算总和
【发布时间】:2013-03-06 10:48:56
【问题描述】:

我有一张像下面这样的表格

 Date        |  Product      |  Qty
-------------|---------------|------
12-Dec-12    | reference1    | 1
14-Dec-12    | reference2    | 2
14-Dec-12    | reference1    | 3
1-Jan-13     | reference2    | 4
3-Jan-13     | reference2    | 5
3-Jan-13     | reference3    | 6

我想通过查询得到它,如下所示

Product    | Dec 2012   | Jan 2013
===========|============|========== 
reference1 |    4       | 0
reference2 |    2       | 9
reference3 |    0       | 6

我已经知道如何分组,我的问题是如何拥有动态列(我希望能够选择最后一个6 months12 months24 months)。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您正在尝试将数据从行透视到列中。 MySQL 没有数据透视函数,但您可以使用带有 CASE 的聚合函数来获得结果:

    select product,
      sum(case when month(date) = 12 and year(date) = 2012 
               then qty else 0 end) Dec2012,
      sum(case when month(date) = 1 and year(date) = 2013 
               then qty else 0 end) Jan2013
    from yourtable
    group by product
    

    SQL Fiddle with Demo

    这也可以写成使用子查询来获取月-年格式的日期:

    select product,
      sum(case when MonthYear = 'Dec_2012' then qty else 0 end) Dec2012,
      sum(case when MonthYear = 'Jan_2013' then qty else 0 end) Jan2013
    from
    (
      select product,
        date_format(date, '%b_%Y') MonthYear,
        qty
      from yourtable
    ) src
    group by product;
    

    SQL Fiddle with Demo

    那么如果你想动态生成一个日期列表或者想要返回一个未知数量的日期,你可以使用prepared statement来生成动态SQL:

    SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'sum(case when MonthYear = ''',
          MonthYear,
          ''' then qty else 0 end) AS ',
          MonthYear
        )
      ) INTO @sql
    FROM 
    (
      select product,
        date_format(date, '%b_%Y') MonthYear,
        qty
      from yourtable
    ) src;
    
    SET @sql = CONCAT('SELECT product, ', @sql, ' 
                       from
                       (
                        select product,
                          date_format(date, ''%b_%Y'') MonthYear,
                          qty
                        from yourtable
                       ) src
                       GROUP BY product');
    
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    SQL Fiddle with Demo。这三个都会给你结果:

    |    PRODUCT | DEC_2012 | JAN_2013 |
    ------------------------------------
    | reference1 |        4 |        0 |
    | reference2 |        2 |        9 |
    | reference3 |        0 |        6 |
    

    【讨论】:

    • 哇哦,4分钟编辑我的帖子,然后给我答案,这是一个真正的表现。谢谢,你发现了我的问题,我不知道去哪里找。我想你的回答我能应付。
    • @VincentAndre 我编辑了我的答案以包含一个动态版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多