0

Before someone mentions it, I have seen the exact same SQL question on Stack before and from my point of view, that's actually transposing columns to rows. What I'm trying to accomplish is as seen below in the photos, given the top one, I want to create a new table with the previous data that is flipped in this sense. enter image description here

enter image description here

2
  • 1
    You can check this stackoverflow.com/q/13372276/6309111 Commented Dec 30, 2020 at 10:06
  • If I was going there, I wouldn't start from here :-( Commented Dec 30, 2020 at 10:07

1 Answer 1

2

You can use the conditional aggregation and union all as follows:

select name_new, 
       max(case when name = 'PersonA' then A end) as PersonA,
       max(case when name = 'PersonB' then A end) as PersonB,
       max(case when name = 'PersonC' then A end) as PersonC
from 
(select name, 'A1' name_new, A1 A from mytable union all
select name, 'A2' name_new, A2 A from mytable union all
select name, 'A3' name_new, A3 A from mytable union all
select name, 'A4' name_new, A4 A from mytable ) t
group by name_new 

SQLFiddle

Sign up to request clarification or add additional context in comments.

11 Comments

what does name_new represent?
see in the sub-query --> (select name, 'A1' name_new, -- I have just given alias to A1, A2 ... Also check updated answer, In final select I have given alias name to name_new
what have i not understood sqlfiddle.com/#!9/997790/4
Ok, alias used in the GROUP BY was not correct. I have updated the answer with SQLFiddle'
one last thing if i was to create a new table with this new format, would I have to go about it manually or? I'm attempting to print all columns that are null for let's say Person A, which is why I was trying to manipulate the table and pass a where clause for null at column Person A
|

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.