简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM