transpose row data into columns

Dom 776 Reputation points
2024-06-08T14:01:19.5733333+00:00

Hope I'm asking this correctly. I have a table in this format:

User's image

I need to have the Unique ID and the account numbers from both stores all in the same record. Like this:
User's image

How can I accomplish this in SQL? Is this some kind of PIVOT or UNPIVOT? What would the syntax be?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,799 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 111.2K Reputation points MVP
    2024-06-08T15:42:08.3566667+00:00
    SELECT "Unique Patron ID",
            MIN(CASE WHEN Store = 'STORE_1' THEN Account# END) AS Store1_Acct,
            MIN(CASE WHEN Store = 'STORE_2' THEN Account# END) AS Store2_Acct
    FROM  tbl
    GROUP BY "Unique Patron ID"
    
    
    

    You could also use the PIVOT operator for this, but the pattern above is more flexible.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. LiHongMSFT-4306 27,016 Reputation points
    2024-06-11T02:41:48.63+00:00

    Hi @Dom

    Try this query using PIVOT:

    SELECT * 
    FROM YourTable 
    PIVOT (MAX([Account#]) FOR STORE IN([STORE_1],[STORE_2])) AS P
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.