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.
Author |
Topic |
cmeier
Starting Member
2 Posts |
Posted - 2015-02-18 : 20:01:11
|
Hi everyoneJust 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 pcwhere 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-- speed50x-- 20.0-- 1233--- 970.0000--- 128-- 800However, i need thisComp---Atributecd-----50xhd-----20.0model--1233price--970.0000ram----128speed--800how 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 @YourTablewhere code=(select max(code) from @YourTable) Result :comp Atributecd 50xhd 20.0model 1233price 970.00ram 128speed 800 |
|
|
cmeier
Starting Member
2 Posts |
Posted - 2015-02-19 : 09:40:52
|
Thank you! |
|
|
|
|
|
|
|