sql - PIVOT 并插入每 N 行

标签 sql sql-server t-sql 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,但无法理解。

最佳答案

与 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/

相关文章:

mysql - 如何使用联接根据特定条件从表中仅选择不同的结果

SQL Server 2008 R2 卡在单用户模式

sql - 具有动态列的数据透视示例

sql-server - 根据多个 xml 属性过滤 XML 节点以进行更新

mysql - 获取最大字段值等于 x 的行

MySQL:优化连接

mysql - 从 SQL 数据库服务器更改为托管服务器的 mySQL

sql-server - 按子句排序的平均值

t-sql - 将 varchar(max) 转换为十进制时,将数据类型 varchar 转换为数字时出错

sql - 在 Access 中连接多个列上的两个大表