SQL Server 将行转换为列而不进行任何计算

nzk0hqpo  于 2023-01-12  发布在  其他
关注(0)|答案(1)|浏览(106)

我有一个只有一列的表。如何将这些行转换为列?
| 颜色代码|
| - ------|
| 编号FFCC00|
| 编号339966|
| 编号800080|
| 编号FF9900|
最大可能行数为10。
我期待着这个:
| C1|C2|C3|四碳|
| - ------|- ------|- ------|- ------|
| 编号FFCC00|编号339966|编号800080|编号FF9900|

o7jaxewo

o7jaxewo1#

我不知道如何动态生成列名,如果你可以组合sql脚本,你可以使用组合字符串脚本来执行。

with code as (
select '#FFCC00' as ColourCode 
union
select '#339966' as ColourCode 
union
select '#800080' as ColourCode 
union
select '#FF9900' as ColourCode )
select *
from
(select ColourCode , 
'C' + cast( ROW_NUMBER() OVER (Order by (select 1)) as nvarchar(max)) as rn -- generate sequence number
from code ) as sourcetable
PIVOT  
(  
  max(ColourCode)  
  FOR rn IN ([C1],[C2],[C3],[C4])  -- predifned column Name, if you want to dynamic generated, you should use variable 
) AS PivotTable;

相关问题