• I hope this is what you require from the above data:

    Declare @sql As Varchar(MAX)

    Select @sql = 'Select paymentID, ' + STUFF((Select Distinct ',SUM(Case When Reason = ' + Char(39) + Reason + Char(39) + ' Then (Case When receivedtype = ''Dr'' Then ReceivedAmout Else -1*ReceivedAmout End) Else '''' End) As ' + Reason From paymenthistory FOR XML PATH('')),1,1,'') + ' From paymentHistory Group By paymentID '

    print @sql

    execute(@sql)

    Test the code and see. Hope this helps. 🙂

    Vinu Vijayan

    For better and faster solutions please check..."How to post data/code on a forum to get the best help" - Jeff Moden[/url] 😉