1

我有程序从各种来源提取数据,给我 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 中实现这一点?

4

2 回答 2

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;
于 2012-08-29T00:00:26.887 回答
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
...
于 2012-08-28T23:55:51.297 回答