【问题标题】:Unpivot multiple columns not showing desire resultUnpivot 多列未显示期望结果
【发布时间】:2015-09-04 14:33:53
【问题描述】:
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

我正在尝试将列还原为行。有些部分会有空值。

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

如果我只使用一列(产品,注释掉代码)执行,那么我将在 ID 列 (1,2) 中有 2 个值。如果我使用 2 列运行查询,那么我在 ID 列中得到 4 个值(1、2、3、4)。

【问题讨论】:

    标签: sql sql-server sql-server-2012-express


    【解决方案1】:

    可能根据我的假设和您提供的数据,我们可以使用 Cross apply 和 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
    

    【讨论】:

    • 感谢您的帮助。 Section2_Product & Section2_Code 可以有值也可以为空,文件有2个以上的section。
    • 只需在 NULL Place 中添加值,然后在 Cross Apply 中添加部分和代码,就像 1 和 2 @user1804925 一样
    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 2019-04-05
    • 2022-08-14
    • 2012-09-26
    • 1970-01-01
    • 2016-04-08
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多