2012-08-28 101 views
1

我有程序從各種來源提取數據給我3非常相似的表。Union,Join,或GroupBy

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中實現這一點,請求se?

+0

爲什麼你不只是有一個表中的所有12個條目? – Codeman

+2

這個問題和答案會給你很多信息 - 有幫助嗎? http://stackoverflow.com/questions/24470/sql-server-pivot-examples –

+0

@ Pheonixblade9 - 這類問題通常是毫無意義的......通常當一個人問這樣的問題時,模式已經定義,並且沒有什麼可以改變它。 –

回答

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 
... 
+0

+1但是最後一個聚合中的票數據是什麼?也可以使用'SUM()'聚合,如在'SUM(CASE樂隊當'新'THEN門票ELSE 0結束)新'# –

+0

@MichaelBerkowski一個錯字:) –

+0

解決完美的問題,謝謝! – kooldave98

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; 
+0

+1用於回答關鍵點。 :) – Taryn

+0

是的,這絕對是一個更好的問題。 – Taryn