col1 123456789...N
我想要如下输出
col-1 | col-2 | col-3 | col-4 |col-5-------------------------------1 | 2 | 3 | 4 |56 | 7 | 8 | 9 |1011 | 12 | 13 | 14 |15
如何从sql-server查询中获取此输出.
解决方法 另一种选择是Dynamic Pivot.这将创建N列.
例
Declare @nCols int = 5Declare @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,'') + ') ) 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 = 5Declare @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,@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('')),'') + ') ) p'Exec(@sql);--Print @sql总结
以上是内存溢出为你收集整理的c# – 如何将单个整数值列拆分为n列?全部内容,希望文章能够帮你解决c# – 如何将单个整数值列拆分为n列?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)