Select [Commodity], [Business Entities], [Quantity]
from MyTable
UNION ALL
SELECT [Commodity], 'TOTAL', SUM([Quantity])
from MyTable
group by [Commodity]
order by [Commodity]
SELECT
Commodity,
[Business Entities] = CASE WHEN GROUPING([Business Entities]) = 1 THEN 'Total' ELSE [Business Entities] END,
Quantity = SUM(Quantity)
FROM YourTabe
GROUP BY GROUPING SETS (
(Commodity, [Business Entities]),
(Commodity)
)
ORDER BY
[Commodity],
GROUPING([Business Entities]),
[Business Entities];
尝试这个。
你可以用
GROUPING SETS
这个该
GROUPING
函数告诉我们列是否已被分组。