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...

3
  • Take a look at 'How to pivot rows into columns'. Commented Aug 30, 2010 at 15:16
  • 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? Commented Aug 30, 2010 at 15:18
  • I want to have a view of the table with this design. Commented Aug 30, 2010 at 15:23

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.