使用SQL Server枢轴与两列主键

问题描述 投票:0回答:2

我有一个表像这样的,我用code1code2作为主键。

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检索好的数据,但它不是这里的问题。在“温度”的列的数目是静态的,所以我可以枢转,因为我喜欢。

sql-server pivot
2个回答
3
投票

您可以使用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;

如果你真的想您所指定的顺序效果,请使用order by 1, 2, 4


0
投票

使用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
© www.soinside.com 2019 - 2024. All rights reserved.