我有程序从各种来源提取数据给我3个非常类似的表。
Metric | Tickets |Band
______________________________________
Acknowledgement | 45 | New
Acknowledgement | 23 | Within
Acknowledgement | 16 | Near
Acknowledgement | 2 | Very Near
和
Metric | Tickets |Band
___________________________________
Escalation | 10 | New
Escalation | 43 | Within
Escalation | 81 | Near
Escalation | 6 | Very Near
和
Metric| Tickets |Band
___________________________________
Fixed | 34 | New
Fixed | 52 | Within
Fixed | 36 | Near
Fixed | 4 | Very Near
现在,我想以某种方式将它们组合在一起,以便像这样有一个表输出
Metric | New | Within | Near | Very Near
_____________________________________________________
Acknowledgement | 45 | 23 | 16 | 2
Escalation | 10 | 43 | 81 | 6
Fixed | 34 | 52 | 36 | 4
我怎样才能在MS SQLServer中实现这一点?
答案 0 :(得分:5)
这不需要为每个表重复所有聚合和CASE表达式 - 只需要一个简单的联合,然后就可以转动它。
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;
答案 1 :(得分:4)
这是一个假的支点,应该得到你想要的。然后,您将为每个表联合此查询。
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
...