有两个表:
第一个表有两列,其中包含以下数据:
[col1] [RowIndex]
apple 1
10 2
red 3
pear 4
20 5
yellow 6
第二个空表有 3 列:
[FruitType] [Weight] [Color]
我希望将第一个表的 [col1] 数据加载到第二个表中,但“旋转”并且没有任何聚合。
结果将如下所示:
[FruitType] [Weight] [Color]
apple 10 red
pear 20 yellow
如何向第二个表插入数据?我尝试过 PIVOT,但无法理解。
最佳答案
与 row_number() 配合使用的条件聚合应该可以解决问题
示例
Declare @YourTable Table ([RowIndex] int,[col1] varchar(50))
Insert Into @YourTable Values
(1,'apple')
,(2,'1')
,(3,'red')
,(4,'pear')
,(5,'2')
,(6,'yellow')
Select [FruitType] = max(case when col=1 then Col1 end)
,[Weight] = max(case when col=2 then Col1 end)
,[Color] = max(case when col=0 then Col1 end)
From (
Select *
,Grp = (Row_Number() over (order by [RowIndex]) - 1) / 3
,Col = Row_Number() over (order by [RowIndex]) % 3
From @YourTable
) A
Group By Grp
返回
FruitType Weight Color
apple 1 red
pear 2 yellow
注意:
如果 RowIndex
是真正连续的,您可以删除 row_number() 函数并简单地使用 RowIndex
关于sql - PIVOT 并插入每 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265799/