2015-09-04 86 views
0
Original 
    RecordKey Name Section1_Product Section1_Code Section2_Product Section2_Code ...... 
    1   a   ff    22    
    2   b   gg    22 
    3   c   hh    33 


    RecordKey  Name  Section  Product  Code ...... 
    1    a   1   ff   22 
    1    a   2 
    2    b   1   gg   22 
    2    b   2 
    3    c   1   hh   22 
    3    c   2 

我想將列轉化爲行。有些部分會有空值。Unpivot多列不顯示慾望結果

SELECT RecordKey 
,Name 
,'Num_of_Sections' = ROW_NUMBER() OVER (PARTITION BY RecordKey ORDER BY ID) 
,Product 
,Code 
FROM (
SELECT RecordKey, Name, Section1_Product, Section1_Code, Section2_Product, Section2_Code FROM Table 
) M 

UNPITVOT (
    Product FOR ID IN (Section1_Product, Section2_Product) 
) p 

UNPIVOT (
    Code FOR CO IN (Section1_Code, Section2_Code) 
) c 

如果我只執行一列(Product,註釋掉代碼),那麼我將在ID列(1,2)中有2個值。如果我用2列運行查詢,那麼我在ID列(1,2,3,4)中得到4個值。

回答

1

可按照規定,我們可以做到這一點使用跨應用和ROW_NUMBER

declare @Record TABLE 
    ([RecordKey] int, 
    [Name] varchar(1), 
    [Section1_Product] varchar(2), 
    [Section1_Code] int, 
    [Section2_Product] varchar(2), 
    [Section2_Code] int) 
; 

INSERT INTO @Record 
    ([RecordKey], [Name], [Section1_Product], [Section1_Code],[Section2_Product],[Section2_Code]) 
VALUES 
    (1, 'a', 'ff', 22,NULL,NULL), 
    (2, 'b', 'gg', 22,NULL,NULL), 
    (3, 'c', 'hh', 33,NULL,NULL) 
; 
    With cte as (
    Select T.RecordKey, 
    T.Name, 
    T.val, 
    T.val1 from (
    select RecordKey,Name,val,val1 from @Record 
    CROSS APPLY (VALUES 
       ('Section1_Product',Section1_Product), 
       ('Section2_Product',Section2_Product))cs(col,val) 
    CROSS APPLY (VALUES 
       ('Section1_Code',Section1_Code), 
       ('Section2_Code',Section2_Code))css(col1,val1) 
    WHERE val is NOT NULL)T 
    ) 
Select c.RecordKey, 
     c.Name, 
     c.RN, 
     CASE WHEN RN = 2 THEN NULL ELSE c.val END Product, 
     c.val1 Code 
      from (
Select RecordKey, 
     Name, 
     ROW_NUMBER()OVER(PARTITION BY val ORDER BY (SELECT NULL))RN, 
     val, 
     val1 from cte)C 
+0

謝謝你幫助我的假設和數據。 Section2_Product&Section2_Code可以具有值或可以爲空,並且該文件具有多於兩個部分。 – user1804925

+0

只需在NULL Place中添加值並在Cross Apply中添加該部分和代碼就像1&2 @ user1804925 – mohan111