I dont think it needs to be dynamic in this case, as he is PIVOTing on the month...can you try this.select a.student_id, a.student_name, max(case when b.[month] = 'Jan' then b.payment else null end) as [payment1], max(case when b.[month] = 'Jan' then b.[month] else null end) as [month1], max(case when b.[month] = 'Feb' then b.payment else null end) as [payment2], max(case when b.[month] = 'Feb' then b.[month] else null end) as [month2], max(case when b.[month] = 'Mar' then b.payment else null end) as [payment3], max(case when b.[month] = 'Mar' then b.[month] else null end) as [month3].....from student ainner join paymentdetails b on a.student_id = b.student_idgroup by a.student_id, a.student_name
EDIT: This result-set makes more sense to me than your expected outputselect a.student_id, a.student_name, max(case when b.[month] = 'Jan' then b.payment else null end) as [Jan], max(case when b.[month] = 'Feb' then b.payment else null end) as [Feb], max(case when b.[month] = 'Mar' then b.payment else null end) as [Mar]from student ainner join paymentdetails b on a.student_id = b.student_idgroup by a.student_id, a.student_name