PIVOT并每N行插入

时间:2018-11-12 15:58:33

标签: sql sql-server tsql sql-server-2014

有两个表:

第一个表有两列,其中包含以下数据:

[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,但无法绕开我的头。

2 个答案:

答案 0 :(得分:2)

与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

答案 1 :(得分:2)

您可以尝试使用ROW_NUMBER窗口函数进行一些计算

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

sqlfiddle