Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top