SQL 服务器:创建一个 table,其中列是一行 - 索引 mod x
SQL Server : create a table where the columns are a row - index mod x
我有一个 table 包含 2 列 - identifier
(1, 2, 3...) 和值。
有必要制作一个table,其中列将是标识符除以 3 的剩余部分。
一个例子:
表 1:
id value
----------
1 aaa
2 bbb
3 ccc
4 ddd
5 eee
6 fff
结果应该是:
0 1 2
----------------
aaa bbb ccc
ddd eee fff
请告诉我如何在 SQL 服务器中执行此操作。
PS。是否可以不使用标识符作为单独的列来实现它,而只使用实际的行号
您可以进行条件聚合。如果 id
从 1
开始并且始终递增,没有间隙,则:
select
max(case when (id - 1) % 3 = 0 then value end) value1,
max(case when (id - 1) % 3 = 1 then value end) value2,
max(case when (id - 1) % 3 = 2 then value end) value3
from from mytable t
group by (id - 1) / 3
否则我们可以生成一个序列 row_number()
:
select
max(case when rn % 3 = 0 then value end) value1,
max(case when rn % 3 = 1 then value end) value2,
max(case when rn % 3 = 2 then value end) value3
from (
select t.*, row_number() over(order by id) - 1 rn
from mytable t
) t
group by rn / 3
迟到的答案,但这里有一个选项,您可以动态定义列数
例子
Declare @Col int = 3
Declare @SQL varchar(max) = stuff( ( Select ',' + QuoteName([N])
From ( Select Top (@Col) N=-1+Row_Number() Over (Order By (Select NULL))
From master..spt_values
) n1
For XML Path('')),1,1,'')
Set @SQL = '
Declare @Col int = '+convert(varchar(10),@Col)+';
Select '+@SQL+'
From (
Select Value
,ColNr=(row_number() over (order by id) - 1) % @Col
,RowNr=(row_number() over (order by id) - 1) / @Col
From #YourTable
) src
Pivot ( max(Value) for ColNr in ('+@SQL+' ) ) pvt '
Exec(@SQL)
Returns
0 1 2
aaa bbb ccc
ddd eee fff
我有一个 table 包含 2 列 - identifier
(1, 2, 3...) 和值。
有必要制作一个table,其中列将是标识符除以 3 的剩余部分。
一个例子:
表 1:
id value
----------
1 aaa
2 bbb
3 ccc
4 ddd
5 eee
6 fff
结果应该是:
0 1 2
----------------
aaa bbb ccc
ddd eee fff
请告诉我如何在 SQL 服务器中执行此操作。
PS。是否可以不使用标识符作为单独的列来实现它,而只使用实际的行号
您可以进行条件聚合。如果 id
从 1
开始并且始终递增,没有间隙,则:
select
max(case when (id - 1) % 3 = 0 then value end) value1,
max(case when (id - 1) % 3 = 1 then value end) value2,
max(case when (id - 1) % 3 = 2 then value end) value3
from from mytable t
group by (id - 1) / 3
否则我们可以生成一个序列 row_number()
:
select
max(case when rn % 3 = 0 then value end) value1,
max(case when rn % 3 = 1 then value end) value2,
max(case when rn % 3 = 2 then value end) value3
from (
select t.*, row_number() over(order by id) - 1 rn
from mytable t
) t
group by rn / 3
迟到的答案,但这里有一个选项,您可以动态定义列数
例子
Declare @Col int = 3
Declare @SQL varchar(max) = stuff( ( Select ',' + QuoteName([N])
From ( Select Top (@Col) N=-1+Row_Number() Over (Order By (Select NULL))
From master..spt_values
) n1
For XML Path('')),1,1,'')
Set @SQL = '
Declare @Col int = '+convert(varchar(10),@Col)+';
Select '+@SQL+'
From (
Select Value
,ColNr=(row_number() over (order by id) - 1) % @Col
,RowNr=(row_number() over (order by id) - 1) / @Col
From #YourTable
) src
Pivot ( max(Value) for ColNr in ('+@SQL+' ) ) pvt '
Exec(@SQL)
Returns
0 1 2
aaa bbb ccc
ddd eee fff