如何在SQL中将行转换为列值

时间:2014-06-16 07:25:33

标签: sql database

我需要帮助将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

有人可以告诉我如何实现这一目标。我以前从未做过这样的询问。

提前致谢, 维奈

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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