CREATE TABLE #foo
(
itemid int,
proddte date,
qty int
);
INSERT #foo(itemid,proddte,qty) VALUES
(1,'20140101',5),(1,'20140102',7),(2,'20150101',10);
-- if it really needs to be a column with the same value
-- in every row, just calculate once and assign it to a variable
DECLARE @sum int = (SELECT SUM(qty) FROM #foo);
SELECT itemid, proddte, GroupedSum = SUM(qty), GrandTotal = @sum
FROM #foo
GROUP BY itemid, proddte;
-- if the grand total can be expressed on its own row,
-- you can use GROUP BY GROUPING SETS:
SELECT itemid, proddte, SUM(qty)
FROM #foo GROUP BY GROUPING SETS((),(itemid,proddte));
-- if that syntax is confusing, you can use a less
-- efficient UNION ALL:
SELECT itemid, proddte, SUM(qty)
FROM #foo GROUP BY itemid,proddte
UNION ALL
SELECT NULL, NULL, SUM(qty)
FROM #foo;
GO
DROP TABLE #foo;
该GROUP BY GROUPING SETS
IS基本上是一个UNION ALL
。这()
意味着SUM
无论分组如何,列出的任何其他组都将单独汇总。尝试GROUP BY GROUPING SETS ((itemid),(itemid,proddte))
看看区别。
有关更多详细信息,请参见文档:
结合使用GROUP BY和ROLLUP,CUBE和GROUPING SETS
如Andriy所述,上面的查询也可以使用以下代码编写:
GROUP BY ROLLUP( (itemid,proddte) )
请注意,两列用另一对括号括起来,使它们成为一个单位。Andriy 编写了一个托管在Stack Exchange Data Explorer上的演示。
GROUP BY ROLLUP((itemid,proddte))
会产生相同的结果,并且可能会减少混乱。