双反轴?

Jua*_*lez 6 sql-server unpivot

我需要取消旋转下表,以便输出如下图所示。

在此处输入图片说明

这是否需要我对数据集执行两次 UNPIVOT,或者我可以通过使用一次 UNPIVOT 并指定所有可用的 Month 和 Value 列来完成我的预期输出吗?

我的脚本应该类似于以下内容来完成我需要的吗?

 Select ID, Name, Age, Gender,Month,Value
    FROM
    (Select ID, Name, Age, Gender,Month1,Month2,Month3,Month4,Value1,Value2,Value3,Value4
    FROM MyTable
    ) as cp
    UNPIVOT 
    (
      Month FOR Months IN (Month1, Month2, Month3,Month4),
      Value for Values IN (Value1,Value2,Value3,Value4)
    ) AS up;
Run Code Online (Sandbox Code Playgroud)

Han*_*non 9

您想要做的是交叉应用而不是 unpivot。这允许对多列进行反透视,而UNPIVOT只允许对单列进行反透视。

像这样的东西:

CREATE TABLE dbo.Struc
(
    ID int NOT NULL
    , Person nvarchar(30) NOT NULL
    , Age int NOT NULL
    , Gender char(1) NOT NULL
    , Month1 int NOT NULL
    , Value1 int NOT NULL
    , Month2 int NOT NULL
    , Value2 int NOT NULL
);

INSERT INTO dbo.Struc (ID, Person, Age, Gender, Month1, Value1, Month2, Value2)
VALUES (1, 'Jane', 20, 'F', 201507, 1, 201508, 0)
    , (2, 'John', 30, 'M', 201507, 0, 201508, 1);

SELECT s.ID
    , s.Person
    , s.Age
    , s.Gender
    , v.Month
    , v.Value
FROM dbo.Struc s
CROSS APPLY (VALUES 
                  (Month1, Value1)
                , (Month2, Value2)
            ) v(Month, Value);
Run Code Online (Sandbox Code Playgroud)

结果:

+----+--------+-----+--------+--------+-------+
| 身份证 | 人 | 年龄 | 性别 | 月 | 价值 |
+----+--------+-----+--------+--------+-------+
| 1 | 简| 20 | F | 201507 | 1 |
| 1 | 简| 20 | F | 201508 | 0 |
| 2 | 约翰 | 30 | 男 | 201507 | 0 |
| 2 | 约翰 | 30 | 男 | 201508 | 1 |
+----+--------+-----+--------+--------+-------+