0

I have searched and tried and have not found the exact SQL code example I am looking for. I have multiple reps per an account (in rows) and need to spread these out into columns. I will have up to 3 for each account.

My source data looks like this:

+---------+-------+------+
| Account | Badge | Name |
+---------+-------+------+
|     123 |   456 | Bob  |
|     123 |   789 | John |
|     123 |   654 | Carl |
+---------+-------+------+

I need it to look like this:

+---------+--------+-------+--------+-------+--------+-------+
| Account | Badge1 | Name1 | Badge2 | Name2 | Badge3 | Name3 |
+---------+--------+-------+--------+-------+--------+-------+
|     123 |    456 | Bob   |    789 | John  |    654 | Carl  |
+---------+--------+-------+--------+-------+--------+-------+

Any help is greatly appreciated.

2
  • 2
    Which dbms are you using? Commented Sep 4, 2018 at 20:52
  • SQL Server 2017 Commented Sep 4, 2018 at 21:39

1 Answer 1

3

You can try this.

If you DBMS support ROW_NUMBER and window function, make row number in a subquery, then do condition aggregate function make pivot

CREATE TABLE T(
   Account INT,
   Badge INT,
   Name VARCHAR(50)

);


INSERT INTO T VALUES (123,456,'Bob');
INSERT INTO T VALUES (123,789,'John');
INSERT INTO T VALUES (123,654,'Carl');

Query 1:

SELECT Account,
      MAX(CASE WHEN rn = 1 THEN Badge end) Badge1,
      MAX(CASE WHEN rn = 1 THEN Name end) Name1,
      MAX(CASE WHEN rn = 2 THEN Badge end) Badge2,
      MAX(CASE WHEN rn = 2 THEN Name end) Name2,
      MAX(CASE WHEN rn = 3 THEN Badge end) Badge3,
      MAX(CASE WHEN rn = 3 THEN Name end) Name3
FROM 
(
    SELECT  *,ROW_NUMBER() OVER(ORDER BY Account) rn
    FROM T
) t1
GROUP BY Account 

Results:

| Account | Badge1 | Name1 | Badge2 | Name2 | Badge3 | Name3 |
|---------|--------|-------|--------|-------|--------|-------|
|     123 |    456 |   Bob |    789 |  John |    654 |  Carl |
Sign up to request clarification or add additional context in comments.

3 Comments

I get Account Badge1 Name1 Badge2 Name2 Badge3 Name3 123 456 Bob 789 John 654 Carl 968 NULL NULL NULL NULL NULL NULL For the rest of the account numbers, the query returns NULL values.
@Gordy It work in sqlfiddle sqlfiddle.com/#!18/c5568/1 or you need to provide more sapmle data from you table
sqlfiddle.com/#!18/c5568/2 you can add WHERE Account IS NOT NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.