如何使用类别和日期总和在SQL中编写此查询

时间:2016-03-01 04:37:12

标签: sql

我在MySQL中有一个表格,其中包含以下数据:

  DATE       Category   AMOUNT
2016-1-1       A         12
2016-1-1       B         10
2016-1-2       A         5
2016-1-3       C         1
2016-2-1       A         5
2016-2-1       B         6
2016-2-2       A         7
2016-2-3       C         3

如何获得如下结果:

MONTH      TOTAL    Category-A  Category-B  Category-C

2016 Jan    28        17          10          1     

2016 Feb    21        12           6          3    

2 个答案:

答案 0 :(得分:0)

如果您正在使用MySQL,这将有效:

SELECT
    DATE_FORMAT(DATE, '%Y %b') AS MONTH,
    SUM(AMOUNT) AS TOTAL,
    SUM(IF(CATEGORY='A', AMOUNT, 0)) AS `Category-A`,
    SUM(IF(CATEGORY='B', AMOUNT, 0)) AS `Category-B`,
    SUM(IF(CATEGORY='C', AMOUNT, 0)) AS `Category-C`
FROM your_table
GROUP BY MONTH;

对于其他数据库引擎,您可能需要稍微更改一下。

答案 1 :(得分:0)

DECLARE @Table1 TABLE 
    (DATE varchar(8), CAT varchar(1), AMOUNT int)
;

INSERT INTO @Table1
    (DATE, CAT, AMOUNT)
VALUES
    ('2016-1-1', 'A', 12),
    ('2016-1-1', 'B', 10),
    ('2016-1-2', 'A', 5),
    ('2016-1-3', 'C', 1),
    ('2016-2-1', 'A', 5),
    ('2016-2-1', 'B', 6),
    ('2016-2-2', 'A', 7),
    ('2016-2-3', 'C', 3)
;


Select  Months,
[A][Category-A],
[B][Category-B],
[C][Category-C],
SUM([A]+[B]+[C])TOTAL
 from (
select CAST(year(DATE) AS VARCHAR)+' '+CONVERT(CHAR(3), DATENAME(MONTH, date))Months,
CAT,
AMOUNT 
from @Table1)T
PIVOT (SUM(AMOUNT) FOR cat IN ([A],[B],[C]))P
GROUP BY Months,[A],[B],[C]
ORDER BY CONVERT(CHAR(3), DATENAME(MONTH, Months)) desc