c# – 如何将单个整数值列拆分为n列?
作者:互联网
我有一个SQL Server表table_name,如:
col1
1
2
3
4
5
6
7
8
9
.
.
.
N
我想要如下输出
col-1 | col-2 | col-3 | col-4 |col-5
-------------------------------
1 | 2 | 3 | 4 |5
6 | 7 | 8 | 9 |10
11 | 12 | 13 | 14 |15
如何从sql-server查询中获取此输出.
解决方法:
另一种选择是Dynamic Pivot.
这将创建N列.
例
Declare @nCols int = 5
Declare @SQL varchar(max) = '
Declare @nCols int = '+str(@nCols,5)+'
Select *
From (
Select RowNr = ((row_number() over (order by col1)-1)/@nCols)+1
,ColNr = concat(''col-'',isnull(nullif((row_number() over (order by col1))%@nCols,0),@nCols))
,Value = col1
From YourTable
) A
Pivot (max(Value) For ColNr in (' + Stuff((Select Top (@nCols) ','+QuoteName(concat('col-',Row_Number() Over (Order By (Select NULL)))) From YourTable For XML Path('')) ,1,1,'') + ') ) p'
Exec(@SQL);
--Print @SQL
返回
如果@nCols = 3,结果为:
EDIT a Fully Parameter Driven Version
这个版本你可以提供
>列数@NbrCols(与上面相同)
>源@FromSrc,它是表名或()中的SQL字符串,即(选择…)
>列名@ColName到Pivot @ColName
> colum前缀@ColPrfx即’Col-‘或””
Declare @NbrCols int = 5
Declare @FromSrc varchar(max) = 'YourTable' -- Or SQL '(Select col ...)'
Declare @ColName varchar(100) = 'col1'
Declare @ColPrfx varchar(100) = 'Col-'
Declare @SQL varchar(max) = '
Declare @NbrCols int = '+str(@NbrCols,5)+'
Select *
From (
Select Row = ((row_number() over (order by '+quotename(@ColName)+')-1)/@NbrCols)+1
,Col = concat('''+@ColPrfx+''',isnull(nullif((row_number() over (order by '+quotename(@ColName)+'))%@NbrCols,0),@NbrCols))
,Val = '+quotename(@ColName)+'
From '+@FromSrc+' A1
) A
Pivot (max(Val) For Col in (' + Stuff((Select Top (@NbrCols) ','+QuoteName(concat(@ColPrfx,Row_Number() Over (Order By (Select NULL)))) From master..spt_values For XML Path('')) ,1,1,'') + ') ) p'
Exec(@SQL);
--Print @SQL
标签:c,sql,sql-server,tsql,sql-server-2012 来源: https://codeday.me/bug/20190714/1458077.html