2010-10-29 42 views
2

我有以下數據返回購買一個簡單的SQL查詢。網站的數量可能會改變,但X,Y,Z是固定的(他們是不同類型的事故,以及存儲的數據代表出現的次數),我需要得到它的格式如下SQL數據透視問題 - 多個聚合?

| Site | X | Y | Z | 
-------------------- 
    A  1 2 3 
    B  4 5 6 
    C  7 8 9 

| A | B | C | 
-------------- 
    1 4 7 
    2 5 8 
    3 6 9 

我有這個迄今爲止

select * 
from Example 
pivot 
(
Max(X) 
for site in ([A],[B],[C]) 
) as p 

但我想我需要多個聚集體(爲X,Y和Z)。

這裏是一個快速腳本來創建基本數據

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
CREATE TABLE [dbo].[Example](
    [Site] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL, 
    [X] [int] NOT NULL, 
    [Y] [int] NOT NULL, 
    [Z] [int] NOT NULL 
) ON [PRIMARY] 

insert into Example(Site, X,Y,Z) Values ('A',1,2,3) 
insert into Example(Site, X,Y,Z) Values ('B',4,5,6) 
insert into Example(Site, X,Y,Z) Values ('C',7,8,9) 

任何幫助,因爲我真的卡住歡迎!

馬克

回答

1

您需要UNPIVOT數據,rePIVOTing其對事故現場之前 - 就像這樣:

select * 
from Example 
unpivot 
(
numbers 
for type in (x,y,z) 
) as p 
pivot 
(
Max(numbers) 
for site in ([A],[B],[C]) 
) as q 
+0

完美的,我現在有工作。 – 2010-10-29 14:26:23