Reputation: 3626
I need to extend my sql query that currently returns sub totals. Is there a way to return both sub totals and grand total with this query:
SELECT oi.PurchaseID, SUM(oi.Quanity * CONVERT(decimal(18,2), p.ItemPrice)) AS sub_total FROM vwPurchaseType oi JOIN tblColor p ON p.ColorID = oi.ColorID WHERE oi.UserID = 1 GROUP BY oi.PurchaseID
Can I create another alias for grand total? I've tried a few different ways and so far I'm leaning toward INSERT the sub_totals into a temp table and returning the value in a stored proc.
Any advice is much appreciated!
Upvotes: 1
Views: 153
Reputation: 1269623
You don't specify the database you are using, but many databases support the with rollup
clause for the group by
:
SELECT oi.PurchaseID,
SUM(oi.Quanity * CONVERT(decimal(18,2), p.ItemPrice)) AS sub_total
FROM vwPurchaseType oi JOIN
tblColor p
ON p.ColorID = oi.ColorID
WHERE oi.UserID = 1
GROUP BY oi.PurchaseID WITH ROLLUP;
This will add an additional row where the PurchaseId
is NULL
. That has the total in it.
Upvotes: 2