PIVOT 并插入每 N 行
PIVOT and insert every N rows
有两个table:
第一个 table 有两列包含以下数据:
[col1] [RowIndex]
apple 1
10 2
red 3
pear 4
20 5
yellow 6
第二个空 table 有 3 列:
[FruitType] [Weight] [Color]
我希望将第一个 table 的 [col1] 数据加载到第二个 "rotated" 并且不进行任何聚合。
结果将如下所示:
[FruitType] [Weight] [Color]
apple 10 red
pear 20 yellow
如何向第二个 table 插入数据?我试过 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
Returns
FruitType Weight Color
apple 1 red
pear 2 yellow
注意:
如果 RowIndex
是 真正连续的 ,您可以删除 row_number() 函数并简单地使用 RowIndex
您可以尝试使用 ROW_NUMBER
window 函数进行一些计算
insert into SecondTable ( FruitType,Weight,Color)
SELECT FruitType,Weight,Color
FROM (
SELECT MAX(CASE WHEN rn % 3 = 1 THEN [col1] END) FruitType,
MAX(CASE WHEN rn % 3 = 2 THEN [col1] END) Weight,
MAX(CASE WHEN rn % 3 = 0 THEN [col1] END) Color
FROM (
SELECT *,ROW_NUMBER() OVER(ORDER BY RowIndex) rn
FROM FirstTable
) tt
GROUP BY (rn - 1) /3
)tt
有两个table:
第一个 table 有两列包含以下数据:
[col1] [RowIndex]
apple 1
10 2
red 3
pear 4
20 5
yellow 6
第二个空 table 有 3 列:
[FruitType] [Weight] [Color]
我希望将第一个 table 的 [col1] 数据加载到第二个 "rotated" 并且不进行任何聚合。
结果将如下所示:
[FruitType] [Weight] [Color]
apple 10 red
pear 20 yellow
如何向第二个 table 插入数据?我试过 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
Returns
FruitType Weight Color
apple 1 red
pear 2 yellow
注意:
如果 RowIndex
是 真正连续的 ,您可以删除 row_number() 函数并简单地使用 RowIndex
您可以尝试使用 ROW_NUMBER
window 函数进行一些计算
insert into SecondTable ( FruitType,Weight,Color)
SELECT FruitType,Weight,Color
FROM (
SELECT MAX(CASE WHEN rn % 3 = 1 THEN [col1] END) FruitType,
MAX(CASE WHEN rn % 3 = 2 THEN [col1] END) Weight,
MAX(CASE WHEN rn % 3 = 0 THEN [col1] END) Color
FROM (
SELECT *,ROW_NUMBER() OVER(ORDER BY RowIndex) rn
FROM FirstTable
) tt
GROUP BY (rn - 1) /3
)tt