Sql server 在SQL server中使用两列作为主键的Pivot

Sql server 在SQL server中使用两列作为主键的Pivot,sql-server,pivot,Sql Server,Pivot,我有一个这样的表,我使用code1和code2作为主键 Code1 Code2 Data1 Data2 Data3 11 0 a b 7 11 1 b b 6 12 2 z v 5 我想将表格转换为: Code1 Code2 TheData (create id ?) 11 0 a 0 11 0

我有一个这样的表,我使用
code1
code2
作为主键

Code1   Code2  Data1 Data2 Data3
 11       0      a     b     7
 11       1      b     b     6 
 12       2      z     v     5 
我想将表格转换为:

Code1    Code2   TheData  (create id ?)
 11        0       a         0
 11        0       b         1
 11        0       7         2
 11        1       b         0
 11        1       b         1
 11        1       6         2
 12        2       z         0
 12        2       v         1
 12        2       5         2
我考虑添加一个id,因为我正在丢失插入的数据的信息

在SQl的后面,我将使用id检索好的数据,但这不是这里的问题。
“temp”中的列数是静态的,因此我可以随意旋转。

您可以使用
union all

select code1, code2, data1 as thedata, 0 as new_id from temp
union all
select code1, code2, data2 as thedata, 1 from temp
union all
select code1, code2, data3 as thedata, 2 from temp;

如果您确实希望结果按指定的顺序排列,请使用
orderby1、2、4

您可以使用
union all

select code1, code2, data1 as thedata, 0 as new_id from temp
union all
select code1, code2, data2 as thedata, 1 from temp
union all
select code1, code2, data3 as thedata, 2 from temp;

如果确实希望结果按指定的顺序排列,请使用
orderby1、2、4

使用UNPIVOT更干净、更有效,请确保以列格式强制转换值

SELECT Code1, Code2, Value, Idname
FROM
(SELECT Code1, Code2,
CAST (Data1 AS varchar) AS Data1, 
    CAST (Data2 AS varchar) AS Data2, CAST (Data3 AS varchar) AS Data3
 FROM @table
) temp
UNPIVOT
(
Value FOR Idname IN (Data1, 
    Data2, Data3)
) as Result

使用UNPIVOT更干净、更高效,请确保以列格式强制转换值

SELECT Code1, Code2, Value, Idname
FROM
(SELECT Code1, Code2,
CAST (Data1 AS varchar) AS Data1, 
    CAST (Data2 AS varchar) AS Data2, CAST (Data3 AS varchar) AS Data3
 FROM @table
) temp
UNPIVOT
(
Value FOR Idname IN (Data1, 
    Data2, Data3)
) as Result

1怎么了?我忘了,马上编辑!1怎么了?我忘了,马上编辑!谢谢,我知道你做了什么。我会试试这个,但使用pivot是否会更有效?我从来没有用过pivot,这次我想用它。@Benoît没有这样的东西。哦,好的。这是因为我的临时表是另一个表的“历史记录n-1”,其中包含最近的值n。在这之后,我需要在表n中插入n-1的行。我以为PIVOT会有帮助,但我想你是对的。谢谢你,我知道你做了什么。我会试试这个,但使用pivot是否会更有效?我从来没有用过pivot,这次我想用它。@Benoît没有这样的东西。哦,好的。这是因为我的临时表是另一个表的“历史记录n-1”,其中包含最近的值n。在这之后,我需要在表n中插入n-1的行。我以为PIVOT会有帮助,但我想你是对的。谢谢
UNPIVOT
不是MySQL操作。对不起,我没有检查自动标记
UNPIVOT
不是MySQL操作。对不起,我没有检查自动标记