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
LVL 8
pzozulkaAsked:
Who is Participating?
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:
SELECT
    t.PartyId,
    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
FROM (
    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
WHERE
    row_num BETWEEN 1 AND 5
GROUP BY t.PartyId
ORDER BY t.PartyId --optional, of course
0

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 ?
0
Scott PletcherSenior DBACommented:
I strongly suspect it could.  Hopefully someone else will look at this issue and take care of that for you.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

É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
0
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.)
0
Scott PletcherSenior DBACommented:
Just curious, why does the query have to use PIVOT?
0
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.
0
Scott PletcherSenior DBACommented:
Hmm, I'd expect my old-style query to typically outperform PIVOT, but that's certainly not guaranteed.
0
PortletPaulfreelancerCommented:
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.
SELECT
      PartyId, [1], [2], [3], [4], [5]
FROM (
      SELECT
            [PartyId]
          , [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
PIVOT (
      MAX([UserReason])
      FOR [row_num] IN ([1], [2], [3], [4], [5])
      ) p
;

Open in new window

0
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.