如何在查询结果中添加汇总行?

时间:2019-08-30 06:41:25

标签: sql sql-server ssms

我需要有关SQL查询的帮助。

以下是创建测试表的查询:

CREATE TABLE test(year_field nvarchar(max), month_field nvarchar(max), category nvarchar(max), items nvarchar(max), code nvarchar(max))
INSERT INTO test(year_field, month_field, category, items, code)
VALUES ('2019','01','C','120','M'),
       ('2019','01','C','20','M'),
       ('2019','01','C','140','M'),
       ('2019','01','C','120','M'),
       ('2019','01','C','80','M'),
       ('2019','01','C','10','M'),
       ('2019','01','C','100','M'),
       ('2019','01','C','210','M'),
       ('2019','01','C','70','M'),
       ('2019','01','C','310',M'),
       ('2019','01','C','10','M'),
       ('2019','01','C','10','O'),
       ('2019','01','C','10','O'),
       ('2019','01','C','100','O'),
       ('2019','01','C','210','O'),
       ('2019','01','C','10','O'),
       ('2019','01','C','70','O'),
       ('2019','01','C','90','O'),
       ('2019','01','C','140','O'),
       ('2019','01','C','70','O'),
       ('2019','01','C','150','O'),
       ('2019','01','C','260','O'),
       ('2019','01','P','10','M'),
       ('2019','01','P','10','M'),
       ('2019','01','P','170','M'),
       ('2019','01','P','70','M'),
       ('2019','01','P','120','M'),
       ('2019','01','P','30','M'),
       ('2019','01','P','10','M'),
       ('2019','01','P','100','M'),
       ('2019','01','P','20','O'),
       ('2019','01','P','30','O')

我编写了一个查询,该查询按 category code 汇总了 items_quantity 字段值。在这里:

SELECT category, code, SUM(items_quantity) FROM ( 

    SELECT year_field, month_field, code, category, 
           SUM((CAST(items as INT)) / 10) items_quantity

    FROM test 
    WHERE (category = 'C' OR category = 'P') 
    GROUP BY year_field, month_field, code, category
) a

WHERE year_field = 2019 AND month_field = 1     
AND (code = 'O' OR code = 'M')
GROUP BY code, category

获得以下结果:

enter image description here

现在我还需要在结果中再增加一行,这将是由代码字段聚合的SUM,如下所示:

enter image description here

它将具有NULL而不是类别,因为这里我们总结了一个代码的所有类别。

有可能做这样的事情吗?

2 个答案:

答案 0 :(得分:2)

尝试将GROUP BY与ROLLUP一起使用

SELECT category, code, SUM(items_quantity) FROM ( 

    SELECT year_field, month_field, code, category, 
           SUM((CAST(items as INT)) / 10) items_quantity

    FROM test 
    WHERE (category = 'C' OR category = 'P') 
    GROUP BY year_field, month_field, code, category
) a

WHERE year_field = 2019 AND month_field = 1     
AND (code = 'O' OR code = 'M')
GROUP BY ROLLUP(code, category)

答案 1 :(得分:-1)

您可以使用union all合并两个结果集

with cte as 
(
    SELECT year_field, month_field, code, category, 
           SUM((CAST(items as INT)) / 10) items_quantity
    FROM test 
    WHERE (category = 'C' OR category = 'P') 
    GROUP BY year_field, month_field, code, category
)

select SELECT category, code, SUM(items_quantity) FROM
cte WHERE year_field = 2019 AND month_field = 1 AND (code = 'O' OR code = 'M')
GROUP BY code, category
union all
select null, code,SUM(items_quantity) from cte where code = 'M'