如何将聚合行添加到查询结果中?

How to add an aggregated row to the result of the query?

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

这是创建测试的查询 table:

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')

我编写了一个查询,它通过 categorycode[ 总结了 items_quantity 字段值=35=]。这是:

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

得到以下结果:

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

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

是否可以这样做?

您可以使用 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'

尝试将 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)