Showing posts with label rollup query. Show all posts
Showing posts with label rollup query. Show all posts

Tuesday, May 24, 2016

Add total row to end of sql result

Problem:
I had an aggregate query which rolled up number for a query.  The customer wanted me to tack on a summary count at the end of the query.  Used the WITH and UNION commands supported in TSQL.


Solution:

;WITH temp as
(
Select
OffenseOther,
[MIL] = SUM(CASE(MilitaryStatus) WHEN 'MIL' THEN 1 ELSE 0 END),
[OTHER] = SUM(CASE(MilitaryStatus) WHEN 'OTHER' THEN 1 ELSE 0 END),
[UNK] = SUM(CASE(MilitaryStatus) WHEN 'UNK' THEN 1 ELSE 0 END),
Count(*) [TOTAL]
From
FcjcRecords
inner join Office o on o.Office_ID = f.Office_ID
inner join MilitaryStatus ms on ms.MilitaryStatus_ID = f.MilitaryStatus_ID
WHERE
f.Offense_ID = 'N'
And
o.Address_ID in (select address_id from Address where LLO_Country = @country)
And
f.Service_ID = @branchOfService
And
f.DateFjCategory between @dateBegin And @dateEnd
And
f.MilitaryStatus_ID is not null
AND
f.FcjcCategory is not null
Group By
f.OffenseOther
)

select OffenseOther,MIL,OTHER,UNK,TOTAL
from Temp
UNION ALL
select 'Total' as TOTAL , SUM(MIL),SUM(OTHER),SUM(UNK),SUM(TOTAL)
from temp



Source:
http://stackoverflow.com/questions/22838347/adding-a-total-row-to-the-end-of-query-result