3

I have a table:

A    B     c
a1   1     a11
a1   2     a12
a1   3     a13
a2   1     a21
a2   2     a22
a2   3     a23

and I want to convert it to:

A     C1     C2     C3
a1    a11    a12    a13
a2    a21    a22    a23

How can I write a SQL query to achieve this... I do not want to convert my table to csv and use python and do it...

Deepank Gupta
  • 1,597
  • 3
  • 12
  • 11
  • Just to clarify some. Do you want to break out the C column into multiple columns based on the values in the B column? Are you trying to replace the first table design or are you trying to write a query which will keep the first table design in place but pull the values for the second table design? – Justin C Aug 30 '10 at 15:18
  • I want to have a view of the table with this design. – Deepank Gupta Aug 30 '10 at 15:23
  • Take a look at ['How to pivot rows into columns'](http://stackoverflow.com/questions/3120835/how-to-pivot-rows-into-columns-custom-pivoting). – Will A Aug 30 '10 at 15:16

1 Answers1

2
SELECT A,
MAX(CASE WHEN B=1 THEN c END) AS C1,
MAX(CASE WHEN B=2 THEN c END) AS C2, // etc for B=3,4
FROM table1
GROUP BY A
a1ex07
  • 36,826
  • 12
  • 90
  • 103