sql server 2008 - How can I transpose multiple lines of data into strings with a unidue ID? -
i have file millions of rows need convert. i'm having trouble getting desired result wanted defer experts;
select [id], min ([date]) 'payment1', min ([date]) 'payment2', 'payment2' > 'payment1' min ([date]) 'payment3', 'payment3' > 'payment2' min ([date]) 'payment4', 'payment4' > 'payment3' [fp&a].[dbo].[paymentschedules] group [id] order [id]
it looks want select 4 lowest distinct dates 4 payments. present easy understand way this:
- find payment1
- join table again find payment2
- join table again find payment3
- ...
the end result here:
with step1 ( select id, min(date) payment1 ps group id ), step2 ( select step1.*, min(date) payment2 step1 join ps on step1.id = ps.id step1.payment1 < ps.date group step1.id, payment1 ), step3 ( select step2.*, min(date) payment3 step2 join ps on step2.id = ps.id step2.payment2 < ps.date group step2.id, payment1, payment2 ), step4 ( select step3.*, min(date) payment4 step3 join ps on step3.id = ps.id step3.payment3 < ps.date group step3.id, payment1, payment2, payment3 ) select * step4
here's fiddle showing in action: http://sqlfiddle.com/#!3/66576/8
now makes 4 joins, performance isn't best. if having problems performance, ranking dates, picking 4 lowest (excluding duplicates), , pivoting table.
Comments
Post a Comment