2011-06-14 160 views
1

,我有以下數據:SQL數據透視表

ID  Data 
1   tera 
1   add 
1   alkd 
2   adf 
2   add 
3   wer 
4   minus 
4   add 
4   ten 

我試圖使用數據透視表,行推入1排,每ID多列。 所以如下:

ID Custom1  Custom2 Custom3 Custom4.......... 
1  tera  add   alkd  
2  adf  add 
3  wer 
4  minus  add   ten 

我迄今以下查詢:

INSERT INTO @SpeciInfo 
(ID, [Custom1], [Custom2], [Custom3], [Custom4], [Custom5],[Custom6],[Custom7],[Custom8],[Custom9],[Custom10],[Custom11],[Custom12],[Custom13],[Custom14],[Custom15],[Custom16]) 
    SELECT 
     ID, 
     [Custom1], 
     [Custom2], 
     [Custom3], 
     [Custom4], 
     [Custom5], 
     [Custom6], 
     [Custom7], 
     [Custom8], 
     [Custom9], 
     [Custom10], 
     [Custom11], 
     [Custom12], 
     [Custom13], 
     [Custom14], 
     [Custom15], 
     [Custom16] 
    FROM SpeciInfo) p 
    PIVOT 
    (
     (
      [Custom1], 
      [Custom2], 
      [Custom3], 
      [Custom4], 
      [Custom5], 
      [Custom6], 
      [Custom7], 
      [Custom8], 
      [Custom9], 
      [Custom10], 
      [Custom11], 
      [Custom12], 
      [Custom13], 
      [Custom14], 
      [Custom15], 
      [Custom16] 
     ) 
    ) AS pvt 
    ORDER BY ID; 

我需要的16場,但我不完全相信我做什麼FROM子句,或者如果我米甚至這樣做是否正確?

感謝

回答

2

如果你追求的是動態生成的列,即通常被稱爲動態交叉,不能在T-SQL來完成,而不訴諸動態SQL(構建查詢字符串),這是不建議。相反,您應該在中間層或報告應用程序中構建該查詢。

如果你只是想一個靜態的解決方案,替代使用的你尋找可能看起來像這樣在SQL Server 2005或更高版本什麼PIVOT:

With NumberedItems As 
    (
    Select Id, Data 
     , Row_Number() Over(Partition By Id Order By Data) As ColNum 
    From SpeciInfo 
    ) 
Select Id 
    , Min(Case When Num = 1 Then Data End) As Custom1 
    , Min(Case When Num = 2 Then Data End) As Custom2 
    , Min(Case When Num = 3 Then Data End) As Custom3 
    , Min(Case When Num = 4 Then Data End) As Custom4 
    ... 
From NumberedItems 
Group By Id 

在原始數據的一個嚴重問題是,有不是序列的指示器,因此係統無法知道給定ID的哪個項目應出現在Custom1列中,而不是Custom2列。在我上面的查詢中,我隨意按名稱排序。