Christopher Yee
Christopher Yee

Reputation: 545

Table formatting trouble

I was just wondering if i could possibly get some help with some code to transform this table:

  ID                             Code      Procedure              
    2012146322968                  4         16830, 16830               
    2012146658928                  6         16837, 16837            

Into this one:

ID              Code4   Procedures4     Code6       Procedures6
2012146322968   4       16830, 16830    NULL        NULL
2012146658928   NULL    NULL            6           16837, 16837    

Thanks a lot for the help, I am tying to learn SQL as I go on my job. I am still very new to SQL. I think i may need to make a new temp table, but it doesnt seem to want to work in the MySQL Command Prompt.

Upvotes: 1

Views: 25

Answers (1)

pala_
pala_

Reputation: 9010

I'm not entirely sure what logic you're using for this, or if that dataset is sufficient to create a query that works for the whole table, but the gist of what you want is this:

select id, 
       case when code = 4 then 4 end code4, 
       case when code = 4 then `procedure` end procedures4,
       case when code = 6 then 6 end code6,
       case when code = 6 then `procedure` end procedures6
from test

demo here

It's worth pointing out that this will give weird results if there are any codes other than 4 or 6, since we are specifically checking for those values in the conditional statements.

Upvotes: 1

Related Questions