Reputation: 790
I have procedures pulling data from various sources to give me 3 VERY similar tables.
Metric | Tickets |Band
______________________________________
Acknowledgement | 45 | New
Acknowledgement | 23 | Within
Acknowledgement | 16 | Near
Acknowledgement | 2 | Very Near
And
Metric | Tickets |Band
___________________________________
Escalation | 10 | New
Escalation | 43 | Within
Escalation | 81 | Near
Escalation | 6 | Very Near
And
Metric| Tickets |Band
___________________________________
Fixed | 34 | New
Fixed | 52 | Within
Fixed | 36 | Near
Fixed | 4 | Very Near
Now, I would like to combine them together in some way to have one table output like this
Metric | New | Within | Near | Very Near
_____________________________________________________
Acknowledgement | 45 | 23 | 16 | 2
Escalation | 10 | 43 | 81 | 6
Fixed | 34 | 52 | 36 | 4
How can I achieve this in MS SQLServer, please ?
Upvotes: 1
Views: 116
Reputation: 280383
This doesn't require repeating all of the aggregates and CASE expressions for each table - just a simple union will do, then you can pivot off of that.
SELECT Metric, [New], [Within], [Near], [Very Near] FROM
(
SELECT Metric, Tickets, Band FROM dbo.table_a
UNION ALL SELECT Metric, Tickets, Band FROM dbo.table_b
UNION ALL SELECT Metric, Tickets, Band FROM dbo.table_c
)
AS x PIVOT
(
MAX(Tickets) FOR Band IN ([New],[Within],[Near],[Very Near])
) AS p;
Upvotes: 5
Reputation: 6683
This is a fake pivot that should get what you want. You would then union this query for each table.
SELECT
Metric,
MAX( CASE Band WHEN 'New' THEN Tickets ELSE '' END ) New,
MAX( CASE Band WHEN 'Within' THEN Tickets ELSE '' END ) Within,
MAX( CASE Band WHEN 'Near' THEN Tickets ELSE '' END ) Near,
MAX( CASE Band WHEN 'Very Near' THEN Tickets ELSE '' END ) [Very Near]
FROM
table
GROUP BY
Metric
UNION
...
Upvotes: 4