按月汇总多个记录

时间:2016-05-20 01:15:32

标签: mysql select group-by sum

我想对多个供应商进行检查以产生一个提供供应商名称的表格,以及12列,每个月每月一个。

CHECK TABLE:
Vendor             Trans. Date    Amount
Able Mfg           2008-01-07     227.32
Acme Wolf Tails    2008-03-01      12.00
Able Mfg           2008-01-23     142.50

NEW TABLE:
Vendor            Jan     Feb     Mar     Apr    May ...
Able Mfg        369.82     0       0      0       0
Acme Wolf Tails                  12.00

这是我到目前为止所拥有的。我收到错误,"子查询返回多行":

select 
    `Pay To`,       
    MONTH(`Transaction Date`) AS `Trans Month`,
    (SELECT 
            SUM(`Charge Amount`)
        FROM `Check Table` 
        WHERE MONTH(`Transaction Date`) = 1
        GROUP BY `Pay To`) as `Jan`,
    (SELECT 
            SUM(`Charge Amount`)
        FROM `Check Table` 
        WHERE MONTH(`Transaction Date`) = 2
        GROUP BY `Pay To`) as `Feb`,
    (SELECT 
            SUM(`Charge Amount`)
        FROM `Check Table` 
        WHERE MONTH(`Transaction Date`) = 3
        GROUP BY `Pay To`) as `Mar`
FROM `Check table`
WHERE `Charge Amount` != 0
GROUP BY `Pay To`
ORDER BY `Pay To`; 

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

Chandan,我很感谢你花时间研究这个。我在页面的右侧找到了答案:

SELECT
  `Pay To`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '01' THEN `Charge Amount` END) AS `Jan`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '02' THEN `Charge Amount` END) AS `Feb`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '03' THEN `Charge Amount` END) AS `Mar`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '04' THEN `Charge Amount` END) AS `Jan`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '05' THEN `Charge Amount` END) AS `May`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '06' THEN `Charge Amount` END) AS `Jun`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '07' THEN `Charge Amount` END) AS `Jul`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '08' THEN `Charge Amount` END) AS `Aug`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '09' THEN `Charge Amount` END) AS `Sep`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '10' THEN `Charge Amount` END) AS `Oct`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '11' THEN `Charge Amount` END) AS `Nov`,
  SUM(CASE WHEN MONTH(`Transaction Date`) = '12' THEN `Charge Amount` END) AS `Dec`
FROM `Check Table`
GROUP BY `Pay To`;

谢谢。