簡體   English   中英

Pivot表格成多列多行

[英]Pivot table into multiple columns and multiple rows

背景我有一個表,其中包含一個帶有逗號分隔字符串的 varchar(它有多個類似於這個問題的行。不幸的是,我無法找到將 csv varchar 更改為臨時表的方法,所以我正在尋找自己拆分它。(我也很感激任何解決這個問題的答案,盡管它可能應該是一個單獨的問題?)。

問題

我已成功拆分字符串,現在正在生成類似於以下內容的 output:

   -------------------------------------
   | Row Index  | Column Index | Value |
   -------------------------------------
   |     0      |      0       | (0,0) |
   |     0      |      1       | (1,0) |
   |     0      |      2       | (2,0) |
   |     1      |      0       | (0,1) |
   |     1      |      1       | (1,1) |
   |     1      |      2       | (2,1) |
   |     2      |      0       | (0,2) |
   |     2      |      1       | (1,2) |
   |     2      |      2       | (2,2) |
   -------------------------------------

我想 pivot 這樣我可以將它插入臨時表,最終結果如下所示:

   -------------------------------------
   | Column 1  | Column 2  | Column 3  |
   -------------------------------------
   |   (0,0)   |   (1,0)   |   (2,0)   |
   |   (0,1)   |   (1,1)   |   (2,1)   |
   |   (0,2)   |   (1,2)   |   (2,2)   |
   -------------------------------------

旁白

  1. 列數是提前知道的,但也歡迎不依賴於此的答案。
  2. 我知道我可以反復左外連接第一個表來獲得這個結果,但這需要每列外連接一次(因為我有大約 9 列,這將是很多重復),我假設還有另一種方法。
  3. 性能不是關鍵,但最終表中將有約 2000 行和 8 列。

使用條件聚合:

select 
    RowIndex
  , Column1 = max(case when ColumnIndex=0 then Value end)
  , Column2 = max(case when ColumnIndex=1 then Value end)
  , Column3 = max(case when ColumnIndex=2 then Value end)
from t
group by RowIndex

extrester演示: http ://rextester.com/QLPHR39222

返回:

+----------+---------+---------+---------+
| RowIndex | Column1 | Column2 | Column3 |
+----------+---------+---------+---------+
|        0 | (0,0)   | (1,0)   | (2,0)   |
|        1 | (0,1)   | (1,1)   | (2,1)   |
|        2 | (0,2)   | (1,2)   | (2,2)   |
+----------+---------+---------+---------+

或使用pivot()

select 
    RowIndex
  , Column1 = [0]
  , Column2 = [1]
  , Column3 = [2]
from t
pivot (max(Value) for ColumnIndex in ([0],[1],[2])) p

這是PIVOT查詢的直接應用程序( 請參閱The Docs ):

select x.[0] Column1
     , x.[1] Column2
     , x.[2] Column3
  from YourData
 pivot (max(Value)
   for [Column Index]
    in ([0], [1], [2]) ) x
 order by x.[Row Index]

返回:

| Column1 | Column2 | Column3 |
|---------|---------|---------|
|   (0,0) |   (1,0) |   (2,0) |
|   (0,1) |   (1,1) |   (2,1) |
|   (0,2) |   (1,2) |   (2,2) |

SQL小提琴

要添加更多列,只需將更多列索引添加到FOR column IN (list)部分,然后將相同的值添加到投影(選擇列表)

我有一個與此非常相似的問題,但唯一的區別是我在 Rox 索引中有超過 3 個,基本上有 400 萬個,列索引有超過 0,1 2 個,這是一個 rep_name 字段,可以有超過 100 個並且不斷變化為新代表添加或刪除。 值字段應過濾為僅具有 3 種類型的團隊,並且應按每個行索引進行旋轉和合並以具有 ex: 'X_team & Y team'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM