Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How can i cover this rows into columns?

Author  Topic 

SuperMiguel
Starting Member

3 Posts

Posted - 2015-02-19 : 11:40:56
Basically this is what im trying to do:

Trying to go from the left table to the right one, whats is the easiest way to get that?

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2015-02-19 : 11:49:27
[code]
select name
, max(case when code = 'Age' then value end) as Age
, max(case when code = 'Sex' then value end) as Sex
, max(case when code = 'Weight' then value end) as Weight
from mytable
group by name
[/code]

However, it is generally considered bad practice to use Code/Value columns as you are doing.
Go to Top of Page

SuperMiguel
Starting Member

3 Posts

Posted - 2015-02-19 : 13:30:42
Thanks for the fast reply, how can i expand that code to do something like this:

Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2015-02-19 : 13:52:14
select name
, max(case when code = 'Age' then value end) as Age
, max(case when code = 'Sex' then value end) as Sex
, case when code = 'Weight' then value end as Weight
from mytable
group by name
, case when code = 'Weight' then value end
Go to Top of Page

SuperMiguel
Starting Member

3 Posts

Posted - 2015-02-19 : 14:15:31
quote:
Originally posted by gbritton

select name
, max(case when code = 'Age' then value end) as Age
, max(case when code = 'Sex' then value end) as Sex
, case when code = 'Weight' then value end as Weight
from mytable
group by name
, case when code = 'Weight' then value end




This is what i get when i run that:

Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2015-02-19 : 16:13:37
can you please provide your source data in a consumable format (no pictures). Preferably CREATE TABLE followed by INSERT INTO
Go to Top of Page
   

- Advertisement -