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

huangapple go评论75阅读模式
英文:

Converting rows to columns without any calculation

问题

我有一个只有一列的表格。如何将这些行转换为列?

| 颜色代码 |
| --- |
| #FFCC00 |
| #339966 |
| #800080 |
| #FF9900 |

最多可能有10行。

我期待的结果是:

| C1 | C2 | C3 | C4 |
| --- | --- | --- | --- |
| #FFCC00 | #339966 | #800080 | #FF9900 |
英文:

I have a table with only a single column. How can I convert these rows to columns?

ColourCode
#FFCC00
#339966
#800080
#FF9900

The maximum possible number of rows will be 10.

I am expecting this:-

C1 C2 C3 C4
#FFCC00 #339966 #800080 #FF9900

答案1

得分: 1

我不知道如何动态生成列名,如果您可以组合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 -- 生成序列号
from code ) as sourcetable
PIVOT  
(  
  max(ColourCode)  
  FOR rn IN ([C1],[C2],[C3],[C4])  -- 预定义列名,如果您想要动态生成,您应该使用变量 
) AS PivotTable;  
英文:

I don't know how to dynamic generated column name, if you can combie sql script, you can use combined string to script to execute .


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;  


huangapple
  • 本文由 发表于 2023年1月9日 15:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定