来自X colums的MS SQL创build1个列
好日子我有这样的例子表:
Culumn1 Column2 Column3 Column4 Column5 Dog 456 Long Short Small Car 454 Blue NULL NULL Fruit 466 Apple Pear NULL
当XY列被放入1列时,我期待这样的表格
Column1 Column2 Column3 Dog 456 Long Dog 456 Short Dog 456 Small Car 454 Blue Fruit 466 Apple Fruit 466 Pear
当表格有超过一千行时,感谢您的意见。
即使我可以在Excel中执行此操作,然后将数据导入到MS SQL中。
您可以使用unpivot如下:
Select * from #unpivotdata unpivot( cols for col in([column3],[column4],[column5])) u
输出如下:
+---------+---------+-------+ | Column1 | column2 | cols | +---------+---------+-------+ | Dog | 456 | Long | | Dog | 456 | Short | | Dog | 456 | Small | | Car | 454 | Blue | | Fruit | 466 | Apple | | Fruit | 466 | Pear | +---------+---------+-------+
SELECT Column1, Column2, Column3 FROM table WHERE Column3 IS NOT NULL UNION ALL SELECT Column1, Column2, Column4 FROM table WHERE Column4 IS NOT NULL UNION ALL SELECT Column1, Column2, Column5 FROM table WHERE Column5 IS NOT NULL
使用UNION ALL
:
SELECT col1, col2, col3 FROM tab UNION ALL SELECT col1, col2, col4 FROM tab WHERE col4 IS NOT NULL SELECT col1, col2, col5 FROM tab WHERE col5 IS NOT NULL;
UnPivot会更高效,但如果列数是未知的。
你很多人注意到只有“ 关键 ”列被识别,所以宽度是dynamic的。
例
Declare @YourTable Table ([Column1] varchar(50),[Column2] varchar(50),[Column3] varchar(50),[Column4] varchar(50),[Column5] varchar(50)) Insert Into @YourTable Values ('Dog',456,'Long','Short','Small') ,('Car',454,'Blue',NULL,NULL) ,('Fruit',466,'Apple','Pear',NULL) Select A.[Column1] ,A.[Column2] ,[Column3] = C.Value From @YourTable A Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData) Cross Apply ( Select Field = a.value('local-name(.)','varchar(100)') ,Value = a.value('.','varchar(max)') From B.XMLData.nodes('/row') as C1(n) Cross Apply C1.n.nodes('./@*') as C2(a) Where a.value('local-name(.)','varchar(100)') not in ('Column1','Column2') ) C
返回