954,174 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Results with Subtotals and Grandtotal

Hi Friends,
Can there be a query that will SELECT fields of a table and group a column (say "CustomerID") and show all its rows along with its subtotals and then its Grandtotal in the result returned?

For Example,

CustID Items Cost ExtraCharges
---------------------------------------------------------------------------------------
A1 Cofee 15.00 2.00
A1 Tea 10.00 2.00
Subtotal: 25.00 4.00
B1 Cofee 24.00 10.00
B1 Tea 29.00 11.00
Subtotal: 53.00 21.00
GrandTotal: 78.00 25.00

RahulV
Junior Poster in Training
92 posts since Jun 2007
Reputation Points: 26
Solved Threads: 0
 

This is more befitting of a report, but it's mostly doable and could be all doable if someone tweaks it a bit.

The following assumes a Sales table with CustID, Items, Cost, and ExtraCharges fields.

Select CustID, Items, Cost, ExtraCharges
From Sales
Union 
Select CustID, 'Subtotal' as Items, Sum(Cost) as Cost, Sum(ExtraCharges) as ExtraCharges
From Sales
Group By CustID
Union 
Select 'ZZZZZZZZZ' as CustID, 'GrandTotal' as Items, Sum(Cost) as Cost, Sum(ExtraCharges) as ExtraCharges
From Sales
Order By CustID, Cost


Results:

A1	Tea	10.00	2.00
A1	Coffee	15.00	2.00
A1	Subtotal	25.00	4.00
B1	Coffee	24.00	10.00
B1	Tea	29.00	11.00
B1	Subtotal	53.00	21.00
ZZZZZZZZZ	GrandTotal	78.00	25.00
apegram
LINQ!
Team Colleague
552 posts since Jan 2010
Reputation Points: 327
Solved Threads: 135
 

The above query by apegram is in general good, except for sort by cost. Typically if there was credit or discount (negative cost). Also grand total shows ugly harcoded custID.
The solution is slight modification to the same, though credit goes to apegram for writing the workable query.

select CustID, Items, Cost, ExtraCharges from (
SELECT '1' orderCol, CustID, Items, Cost, ExtraCharges FROM Sales
Union 
Select '2' orderCol, CustID, 'Subtotal' as Items, Sum(Cost) as Cost, Sum(ExtraCharges) as ExtraCharges
From Sales
Group By CustID
Union 
Select '99' orderCol, '' as CustID, 'GrandTotal' as Items, Sum(Cost) as Cost, Sum(ExtraCharges) as ExtraCharges
From Sales
) as t1
 Order By case when orderCol=99 then 1 else 0 end, CustID, orderCol, items
padtes
Junior Poster in Training
86 posts since Aug 2009
Reputation Points: 53
Solved Threads: 20
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You