2013-10-23 24 views
0

我想將行轉換爲列但包含一種數據。需要將行轉換爲有排序的列

樣本數據 例如:

+-----+------+------+ 
| CId | Cat1 | cat2 | 
+-----+------+------+ 
| 1 | 10 | 6 | 
| 1 | 230 | 100 | 
| 2 | 1222 | 30 | 
| 3 | 2 | 50 | 
| 4 | 33 | 21 | 
| 1 | 33 | 13 | 
+-----+------+------+ 

預計輸出

+-----+------+-----+-----+-----+-----+-----+ 
| CId | Rw1 | Rw2 | Rw3 | Rw4 | Rw5 | Rw6 | 
+-----+------+-----+-----+-----+-----+-----+ 
| 1 | 10 | 33 | 230 | 6 | 13 | 100 | 
| 2 | 1222 | 30 | 0 | 0 | 0 | 0 | 
| 3 | 2 | 50 | 0 | 0 | 0 | 0 | 
| 4 | 33 | 21 | 0 | 0 | 0 | 0 | 
+-----+------+-----+-----+-----+-----+-----+ 

查看如何CID: 1排序的所有值Cat1這樣做了之後,需要重新梳理cat2,一切都應該在一排。

請讓我知道如何去做。

+0

你會總是隻有6個最後的列?或者列數是否未知? – Taryn

+0

如果有必要,我將有大約10列,並準備好列名中的手動鍵 – user1810575

回答

3

您可以通過取消轉移和旋轉數據來獲得結果,但是您也希望使用row_number()來保持數據的順序。

第一步是查詢您當前的數據和應用row_number()通過cat1cat2以獲得每個行的值,由cid分區,並下令:

select cid, cat1, cat2, 
    row_number() over(partition by cid order by cat1, cat2) seq 
from yourtable 

Demo。一旦獲得數據,那麼您將將多個列cat1cat2轉化爲具有多行的單個列。您可以使用UNPIVOT功能,也可以使用交叉應用到數據轉換:

select cid, value 
    , 'rw'+cast(row_number() over(partition by cid order by col, seq) as varchar(10)) rw 
from 
(
    select cid, cat1, cat2, 
    row_number() over(partition by cid order by cat1, cat2) seq 
    from yourtable 
) d 
cross apply 
(
    select 1, cat1 union all 
    select 2, cat2 
) c (col, value) 

Demo。當您轉移數據時,您將再次應用row_number(),這將用於創建新的列名稱。此次應用時,您將按cid對數據進行分區,並按您的列cat1/cat2(我使用的1/2)以及您原始創建的序列對其進行排序。這個新的行數將創建所有新列標題,它會守在順序數據要在顯示它

最後將應用旋轉功能:

select cid, 
    coalesce(rw1, 0) rw1, 
    coalesce(rw2, 0) rw2, 
    coalesce(rw3, 0) rw3, 
    coalesce(rw4, 0) rw4, 
    coalesce(rw5, 0) rw5, 
    coalesce(rw6, 0) rw6 
from 
(
    select cid, value 
    , 'rw'+cast(row_number() over(partition by cid order by col, seq) as varchar(10)) rw 
    from 
    (
    select cid, cat1, cat2, 
     row_number() over(partition by cid order by cat1, cat2) seq 
    from yourtable 
) d 
    cross apply 
    (
    select 1, cat1 union all 
    select 2, cat2 
) c (col, value) 
) src 
pivot 
(
    max(value) 
    for rw in (rw1, rw2, rw3, rw4, rw5, rw6) 
) piv; 

SQL Fiddle with Demo 。這給出了最終結果:

| CID | RW1 | RW2 | RW3 | RW4 | RW5 | RW6 | 
|-----|------|-----|-----|-----|-----|-----| 
| 1 | 10 | 33 | 230 | 6 | 13 | 100 | 
| 2 | 1222 | 30 | 0 | 0 | 0 | 0 | 
| 3 | 2 | 50 | 0 | 0 | 0 | 0 | 
| 4 | 33 | 21 | 0 | 0 | 0 | 0 |