SQL Pivot: Need to convert rows into columns

All examples of SQL pivot that I've come across are of numerical data, sum, avg, etc. I need to convert rows of comments into 5 columns.

Current data:

PartyId     UserReason
1                Auto Interest
1                Interest Refund
1                Late Fee
1                Refund
1                Write Off
1                Interest Refund
1                Auto Refund
2                Late Fee
2                Refund
2                Interest Refund

The report results need to display 5 columns ordered by oldest to newest by the primary key.
select top 5 t.PartyId, t.UserReason
from [Transaction] t
where t.NonCashTransactionTypeId is not null
order by t.TransactionId desc

Open in new window

Wanted Results:

PartyId        UserReason1       UserReason2      UserReason3       UserReason4        UserReason5
1                   Auto Interest       Interest Refund   Late Fee               Refund                   Write Off
2                   Late Fee               Refund                  Interest Refund   NULL                      NULL
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
    MAX(CASE WHEN row_num = 1 THEN t.UserReason END) AS UserReason1,
    MAX(CASE WHEN row_num = 2 THEN t.UserReason END) AS UserReason2,
    MAX(CASE WHEN row_num = 3 THEN t.UserReason END) AS UserReason3,
    MAX(CASE WHEN row_num = 4 THEN t.UserReason END) AS UserReason4,
    MAX(CASE WHEN row_num = 5 THEN t.UserReason END) AS UserReason5
    SELECT t.PartyId, t.UserReason,
        ROW_NUMBER() OVER(PARTITION BY t.PartyId ORDER BY t.TransactionId DESC) AS row_num
    FROM [Transaction] t
) AS subquery
    row_num BETWEEN 1 AND 5
GROUP BY t.PartyId
ORDER BY t.PartyId --optional, of course

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
pzozulkaAuthor Commented:
Can this be done using PIVOT ?
Scott PletcherSenior DBACommented:
I strongly suspect it could.  Hopefully someone else will look at this issue and take care of that for you.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Éric MoreauSenior .Net ConsultantCommented:
does it have to be columns or can it be a single string? have a look at http://emoreau.com/Entries/Blogs/2009/10/SQL-Concatenate-values-multiple-from-multiple-lines.aspx
pzozulkaAuthor Commented:
Columns would be ideal, as this data will be passed to C# code behind for further processing. It would make it more difficult to parse a string of data, some of which can contain all sorts of characters that could be considered delimiters (commas, periods, spaces, slashes, etc.)
Scott PletcherSenior DBACommented:
Just curious, why does the query have to use PIVOT?
pzozulkaAuthor Commented:
This will be part of a larger query, that will be executed in a production environment with HUGE amounts  of records. We have a 10 minute timeout window, and if this query does not finish within this window, it will fail. After doing a bit of research, it seems like PIVOT would be the best solution for performance.

Other than that, no reason, and your original solution works perfectly in terms of the desired results.
Scott PletcherSenior DBACommented:
Hmm, I'd expect my old-style query to typically outperform PIVOT, but that's certainly not guaranteed.
PortletPaulEE Topic AdvisorCommented:
sorry, this is late:

"it seems like PIVOT would be the best solution for performance."
why? on what basis? because you expect the SQL to be shorter?
I'm not convinced it's faster either.

anyway, the pivot syntax isn't too hard although I still prefer using the older method.
      PartyId, [1], [2], [3], [4], [5]
          , [UserReason]
          , ROW_NUMBER() OVER(PARTITION BY t.PartyId 
                              ORDER BY (select NULL)) AS row_num --<< choose column(s) to order by
      FROM [Transaction] t
      ) sourcedata
      FOR [row_num] IN ([1], [2], [3], [4], [5])
      ) p

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.