-3

I need a help to convert sql table rows into columns.

Shown below is the sample data:

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

I want to convert this into:

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

Can someone please tell me how to achieve this. I have never done such queries before.

Thanks in advance , Vinay

TechDo
  • 18,398
  • 3
  • 51
  • 64
vinay
  • 5
  • 1

3 Answers3

1

A solution that works with 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

Also, read this article.

Barranka
  • 20,547
  • 13
  • 65
  • 83
1

You can Create a Pivot Table in SQL Server

Select col1, col2, col3, col4 
from tablname
Pivot 
(
Sum(col) for tablname in ([col2],[col3],[col4])
) 
 as PivotTable
Barranka
  • 20,547
  • 13
  • 65
  • 83
Friyank
  • 469
  • 3
  • 8
  • I think you mean SQL server... am I right? Remember: SQL is short for "structured query language", not for a specific RDBMS. – Barranka Jun 16 '14 at 07:41
  • ya, its for SQL Server only, Use Pivot table, and convert rows into column name – Friyank Jun 16 '14 at 08:40
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 solution

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

--sql server with dynamic 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)

--this might work in sql-server mysql oracle or other RDBMS? (as answered by Barranka)

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
vhadalgi
  • 7,027
  • 6
  • 38
  • 67