I have two tables in SQL Server 2008 created like:
CompletedRecordsFinal
:
IF OBJECT_Id('tempdb..#CompletedRecordsFinal') IS NOT NULL
DROP TABLE #CompletedRecordsFinal
SELECT
C1, C2, C3, COUNT(distinct Id) as TotalRecords
INTO
#CompletedRecordsFinal
FROM
#CompletedRecords
GROUP BY
C1, C2, C3
Example result:
C1 C2 C3 TotalRecords
A B 1 50
A B 2 100
WaitRecordsFinal
:
IF OBJECT_Id('tempdb..#WaitRecordsFinal') IS NOT NULL
DROP TABLE #WaitRecordsFinal
SELECT
C1, C2, C3, COUNT(distinct Id) as TotalWaitRecords
INTO
#WaitRecordsFinal
FROM
#WaitRecords
GROUP BY
C1, C2, C3
Example result:
C1 C2 C3 TotalWaitRecords
A B 1 20
A B 2 30
I use these tables with a left outer join like:
SELECT
w.C1, C.C2, w.C3, TotalWaitRecords, TotalRecords
FROM
#WaitingRecordsFinal w
LEFT OUTER JOIN
#CompletedRecordsFinal c ON c.C1 = w.C1
AND c.C2 = w.C2
AND c.C3 = w.C3
What I want is to add a total row at the bottom and I couldn't manage it. I feel I am close but nothing worked like I wanted up to now. I need something like (it doesn't work):
SELECT
w.C1, C.C2, w.C3, TotalWaitRecords, TotalRecords
FROM
#WaitingRecordsFinal w
LEFT OUTER JOIN
#CompletedRecordsFinal c ON c.C1 = w.C1
AND c.C2 = w.C2
AND c.C3 = w.C3
UNION
SELECT
C1 = 'Total', C2 = 'Total', C3 = -1, TotalWaitRecords, TotalRecords
FROM
#WaitingRecordsFinal w
LEFT OUTER JOIN
#CompletedRecordsFinal c ON c.C1 = w.C1
AND c.C2 = w.C2
AND c.C3 = w.C3
Example output of what I want:
C1 C2 C3 TotalRecords TotalWaitRecords
A B 1 50 20
A B 2 100 30
Total Total -1 150 50
Any help would be appreciated.
EDIT: My problem is a little different than the one indicated as duplicate subject. The main problem is I have 3 column for group by. therefore when I do group by C1, C2, C3, with rollup
I see that:
.....
X B -1 300 500
X Total -1 300 500
.....
A B -1 56 47
A Total -1 56 47
Total Total -1 356 547
I just need the most bottom row, not the others. So this solution does not help. How can I get rid of the others except the most bottom Total Total one?