I can't seem to figure out here is how to add that grand total line. I tried rollup and group sets but it just doubled the cumsum and the sumprice which I don't want.
This is what I need to mimick:
This is what I have so far:
SELECT
YEAR(s.OrderDate) AS Year,
MONTH(s.OrderDate) AS Month,
SUM(sd.UnitPrice) AS Sum_Price,
SUM(SUM(sd.UnitPrice)) OVER (PARTITION BY YEAR(OrderDate) ORDER BY MONTH(OrderDate)) AS CumSum
FROM
Sales.SalesOrderDetail sd
JOIN Sales.SalesOrderHeader s ON s.SalesOrderID = sd.SalesOrderID
GROUP BY
YEAR(s.OrderDate), MONTH(s.OrderDate)
ORDER BY
Year, Month;
I am using AdventureWorks2019
2条答案
按热度按时间cgh8pdjw1#
You can use
GROUPING SETS
for this. TheGROUPING
function will tell you if a column has been grouped up in that row. It returns0
for a non-aggregated row, and1
for a rollup.You can also use a partial
ROLLUP
, although it's less clear what's going on. It compiles to the same thing, so efficiency will be the same. You can still useGROUPING()
with this method.agxfikkp2#
I don't use this often so this might be off (I tend to let the client code or reporting tool handle the summaries), but try
ROLLUP
like this: