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 2005 Forums
 Transact-SQL (2005)
 Need help with query to show rows as columns

Author  Topic 

mtl777
Yak Posting Veteran

63 Posts

Posted - 2014-09-18 : 16:50:25
I have a table called Notes that has the ID, CustomerNo, NoteDate, and NoteText. I would like to make a query that will show the 3 most recent notes for each customer, but these 3 notes need to be shown as several columns in only one row, thus:

CustomerNo, NoteDate1, NoteText1, NoteDate2, NoteText2, NoteDate3, NoteText3

How do i do this in a most efficient manner?

Thanks!

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-09-18 : 17:03:44
Try this out (untested, no access to SQL server at the moment)


with notes as (
select CustomerNo, NoteDate, NoteText
rn = row_number() over(partition by CustomerNo
order by NoteDate desc)
from Notes
)

select CustomerNo,
max(case when rn = 1 then NoteDate end) as NoteDate1,
max(case when rn = 1 then NoteText end) as NoteText1,
max(case when rn = 2 then NoteDate end) as NoteDate2,
max(case when rn = 2 then NoteText end) as NoteText2,
max(case when rn = 3 then NoteDate end) as NoteDate3,
max(case when rn = 3 then NoteText end) as NoteText3,
from notes
where rn <= 3
group by CustomerNo

Go to Top of Page

mtl777
Yak Posting Veteran

63 Posts

Posted - 2014-09-18 : 19:06:06
Awesome! After correcting for missing and extra commas, it worked!

Thank you so much!
Go to Top of Page
   

- Advertisement -