Edward Bagby Edward Bagby - 3 years ago 118
SQL Question

After creating a union of two tables in SQL, how to show sum from each table in a single line within SSRS Tablix

I'm trying to create a tablix in SSRS where a single row shows the SUM of work quantities for the TypeOfWork, from two separate database tables.

I created a dataset with a Union (sql shown is simplified, but is the basic idea) that allowed me to have sums of each type of work within each table--by way of how I did the grouping. I can show the two sums, for each type of work, from the two tables in their own line on the SSRS Tablix, easily. Such as:

Work Area | Type of Work | New Table Sum

Work Area | Type of Work | Old Table Sum

...and repeat

But how to show the sums in a single line, as such:

Work Area | Type of Work | New Table Sum | Old Table Sum

Here's the basic SQL:

SELECT SourceTable, WorkArea, TypeOfWork, Sum(WorkAmount)
FROM

(
SELECT 'OldTable' AS SourceTable, o.*
FROM Old o

UNION ALL

SELECT

'NewTable' AS SourceTable
, NEWID()
, '2A077AC6-8040-49CB-B1FD-CD96D0A30533' AS [OldGuid]
, n.*

FROM New n

) AS ReportTable

GROUP BY WorkArea, TypeOfWork, SourceTable

Answer Source

You can use a CASE statement in your top query:

SELECT WorkArea
    , TypeOfWork
    , OldTableSum = SUM(CASE WHEN ReportTable.SourceTable = 'OldTable' THEN WorkAmount ELSE 0 END)  
    , NewTableSum = SUM(CASE WHEN ReportTable.SourceTable = 'NewTable' THEN WorkAmount ELSE 0 END)  
FROM 

(
SELECT 'OldTable' AS SourceTable, o.*
FROM Old o

UNION ALL

SELECT 
    'NewTable' AS SourceTable
    , NEWID()
    , '2A077AC6-8040-49CB-B1FD-CD96D0A30533' AS [OldGuid]
    , n.*
FROM New n

) AS ReportTable

GROUP BY WorkArea, TypeOfWork
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download