2015-09-04 29 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