【问题标题】:How to convert rows into column values in SQL [closed]如何在 SQL 中将行转换为列值 [关闭]
【发布时间】:2014-08-05 23:20:14
【问题描述】:

我需要帮助将 sql 表行转换为列。

下图为示例数据:

Col1    Col2    Col3
1       A       12
1       B       23
1       C       43
2       A       32
2       B       54
2       C       76

我想把它转换成:

Col1    A       B       C
1       12      23      43
2       32      54      76

谁能告诉我如何实现这一点。我以前从未做过这样的查询。

提前致谢, 维奈

【问题讨论】:

标签: sql database


【解决方案1】:

适用于 MySQL 的解决方案:

select 
    col1,
    sum(case col2 when 'A' then col3 end) as A,
    sum(case col2 when 'B' then col3 end) as B,
    sum(case col2 when 'C' then col3 end) as C
from
    yourTable
group by
    col1

另外,请阅读this article

【讨论】:

    【解决方案2】:
    create table #t(Col1 int,Col2 varchar(1),Col3 int)
    insert into #t values(1,'A', 12),
    (1,'B',23),
    (1,'C',43),
    (2,'A',32),
    (2,'B',54),
    (2,'C',76)
    

    -- sql server解决方案

    select * from #t
        pivot
        (
        max(col3)
        for col2 in([A],[B],[c])
        )as piv;
    

    --sql serverdynamic sql example

    declare @cols nvarchar(max);
    declare @query nvarchar(max);
    
    select @cols=stuff((select distinct ','+QUOTENAME(col2) from #t for xml path(''),TYPE).value('.','nvarchar(max)') ,1,1,'');
    
    select @query='select * from #t
    pivot
    (
    max(col3)
    for col2 in('+@cols+')
    )as piv;' 
    
    exec(@query)
    

    --这可能适用于sql-server mysql oracle 或其他RDBMS? (由巴兰卡回答)

    select 
        col1,
        sum(case col2 when 'A' then col3 end) as A,
        sum(case col2 when 'B' then col3 end) as B,
        sum(case col2 when 'C' then col3 end) as C
    from
        #t
    group by
        col1
    

    【讨论】:

      【解决方案3】:

      您可以在 SQL Server 中创建数据透视表

      Select col1, col2, col3, col4 
      from tablname
      Pivot 
      (
      Sum(col) for tablname in ([col2],[col3],[col4])
      ) 
       as PivotTable
      

      【讨论】:

      • 我认为您的意思是 SQL 服务器......我说的对吗?请记住:SQL 是“结构化查询语言”的缩写,而不是特定 RDBMS。
      • 是的,它仅适用于 SQL Server,使用数据透视表,并将行转换为列名
      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多