2011-10-06 103 views
3

我有一個查詢(選擇[型]中,a,B,C,d,從MyTable的E),返回:簡單數據樞軸

[type], [a], [b], [c], [d], [e] 
type 1, x , x , x , x , x 
type 2, x , x , x , x , x 
type 3, x , x , x , x , x 

我想以樞轉所述數據,以便它作爲顯示:

[]  , [type 1], [type 2], [type 3] 
[a] , x  , x  , x 
[b] , x  , x  , x 
[c] , x  , x  , x 
[d] , x  , x  , x 
[e] , x  , x  , x 

SQL的任何指針在這裏將不勝感激。

+0

類型是否修復? –

+0

列a,b,c,d,e是固定的,但可能有X行(類型) – Mattl

+0

我只需要旋轉表,數據不需要分組,即[type]列中的類型將永遠是獨一無二的。 – Mattl

回答

1

我們需要的是:

SELECT Col, [type 1], [type 2], [type 3] 
FROM (SELECT [type], Amount, Col 
     FROM (SELECT [type], [a], [b], [c], [d], [e] 
       FROM _MyTable) as sq_source 
       UNPIVOT (Amount FOR Col IN ([a], [b], [c], [d], [e])) as sq_up) as sq 
PIVOT (MIN(Amount) FOR [type] IN ([type 1], [type 2], [type 3])) as p; 

但由於類型數量是不確定的,我們必須這樣做動態

DECLARE @cols NVARCHAR(2000) 
SELECT @cols = COALESCE(@cols + ',[' + [type] + ']', 
         '[' + [type] + ']') 
FROM _MyTable 
ORDER BY [type] 

DECLARE @query NVARCHAR(4000) 
SET @query = N'SELECT Col, ' + @cols + ' 
FROM (SELECT [type], Amount, Col 
     FROM (SELECT [type], [a], [b], [c], [d], [e] 
       FROM _MyTable) as sq_source 
       UNPIVOT (Amount FOR Col IN ([a], [b], [c], [d], [e])) as sq_up) as sq 
PIVOT (MIN(Amount) FOR [type] IN (' + @cols + ')) as p;'; 

EXECUTE(@query) 

但要小心,因爲查詢技術上來說是一種注射媒介。

+0

值得注意的是,即使您將@cols和@query更改爲nvarchar(max),對於超過4096個「類型」的任何內容也會中斷。看到這裏:http://msdn.microsoft.com/en-us/library/ms143432.aspx –

+0

謝謝,這正是我現在想要的。我將在稍後處理注射問題! – Mattl

1

這樣的事情?

create table #test 
(
type varchar(10), 
a varchar(10), 
b varchar(10), 
c varchar(10), 
d varchar(10), 
e varchar(10) 
) 

insert into #test values 
('type 1', 'x' , 'x' , 'x' , 'x' , 'x'), 
('type 2', 'x' , 'x' , 'x' , 'x' , 'x'), 
('type 3', 'x' , 'x' , 'x' , 'x' , 'x') 

select * from 
(

    select * from 
    (
     select * from #test 
    )data_to_unpivot 
    UNPIVOT 
    (
    Orders FOR [xxx] IN (a,b,c,d,e) 

    )UNPIVOTED_DATA 
)data_to_pivot 
PIVOT 
(
MAX(orders) for type in ([type 1],[type 2],[type 3]) 
)PIVOTED_DATA 
+0

這個硬編碼類型(類型1,類型2,類型3)。我之前評論說,類型是可變的。 – Mattl