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

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

Converting rows to columns without any calculation

问题

  1. 我有一个只有一列的表格。如何将这些行转换为列?
  2. | 颜色代码 |
  3. | --- |
  4. | #FFCC00 |
  5. | #339966 |
  6. | #800080 |
  7. | #FF9900 |
  8. 最多可能有10行。
  9. 我期待的结果是:
  10. | C1 | C2 | C3 | C4 |
  11. | --- | --- | --- | --- |
  12. | #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脚本,可以使用组合的字符串来执行脚本。

  1. with code as (
  2. select '#FFCC00' as ColourCode
  3. union
  4. select '#339966' as ColourCode
  5. union
  6. select '#800080' as ColourCode
  7. union
  8. select '#FF9900' as ColourCode )
  9. select *
  10. from
  11. (select ColourCode ,
  12. 'C' + cast( ROW_NUMBER() OVER (Order by (select 1)) as nvarchar(max)) as rn -- 生成序列号
  13. from code ) as sourcetable
  14. PIVOT
  15. (
  16. max(ColourCode)
  17. FOR rn IN ([C1],[C2],[C3],[C4]) -- 预定义列名,如果您想要动态生成,您应该使用变量
  18. ) 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 .

  1. with code as (
  2. select '#FFCC00' as ColourCode
  3. union
  4. select '#339966' as ColourCode
  5. union
  6. select '#800080' as ColourCode
  7. union
  8. select '#FF9900' as ColourCode )
  9. select *
  10. from
  11. (select ColourCode ,
  12. 'C' + cast( ROW_NUMBER() OVER (Order by (select 1)) as nvarchar(max)) as rn -- generate sequence number
  13. from code ) as sourcetable
  14. PIVOT
  15. (
  16. max(ColourCode)
  17. FOR rn IN ([C1],[C2],[C3],[C4]) -- predifned column Name, if you want to dynamic generated, you should use variable
  18. ) 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:

确定