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
 General SQL Server Forums
 New to SQL Server Programming
 simple transpose

Author  Topic 

cmeier
Starting Member

2 Posts

Posted - 2015-02-18 : 20:01:11
Hi everyone
Just getting started with SQL, and have been doing some excercises online. Eventually I stumbled with a question I can't answer.

I have a query which looks like this:


select cd, hd, model, price, ram, speed from pc
where code = (select max(code) from pc)


it will return the attributes of the record with the largest code number.

like this:

cd--- hd---- model-- price------ ram-- speed
50x-- 20.0-- 1233--- 970.0000--- 128-- 800

However, i need this

Comp---Atribute
cd-----50x
hd-----20.0
model--1233
price--970.0000
ram----128
speed--800

how do i do this??

i read a bit about PIVOT but i cant figure out how to use it, since pivot usually uses some function like max() or sum() to group data. i cant do that here.

Thanks in advance!

pradeepbliss
Starting Member

28 Posts

Posted - 2015-02-19 : 04:22:22
select 'cd' as 'comp',cd as 'Atribute' from @YourTable where code=(select max(code) from @YourTable)
union all
select 'hd' as 'comp',hd as 'Atribute' from @YourTable where code=(select max(code) from @YourTable)
union all
select 'model' as 'comp',model as 'Atribute' from @YourTable where code=(select max(code) from @YourTable)
union all
select 'price' as 'comp',price as 'Atribute' from @YourTable where code=(select max(id) from TestUnPivot)
union all
select 'ram' as 'comp',ram as 'Atribute' from @YourTable where code=(select max(code) from @YourTable)
union all
select 'speed' as 'comp',speed as 'Atribute' from @YourTable
where code=(select max(code) from @YourTable)

Result :

comp Atribute
cd 50x
hd 20.0
model 1233
price 970.00
ram 128
speed 800
Go to Top of Page

cmeier
Starting Member

2 Posts

Posted - 2015-02-19 : 09:40:52
Thank you!
Go to Top of Page
   

- Advertisement -