0

I have a SQL table that has mulitiple rows of data for a user. I want to query that data and return one row for each user. So I want to take the multiple rows and combine them into one row with multiple columns. Is this possible?

Here is what I currently have

UserID   Value
8111     396285
8111     812045789854
8111     Secretary

Here is what I am after

UserID     Column1     Column2        Column3
8111       396285      812045789854   Secretary
4
  • I don't use this enough to be able to give you the syntax off the top of my head. But what you want is the PIVOT command: msdn.microsoft.com/en-ca/library/ms177410(v=sql.105).aspx Edit: Or maybe it's UNPIVOT, regardless both are covered in that link. Commented Apr 19, 2013 at 16:43
  • It would be PIVOT, but that option is only available to him if his RDBMS supports it - MySQL, for example, does not. Commented Apr 19, 2013 at 16:52
  • In MS SQL Server PIVOT only works if there is a third column whose value can be used as the column in the result set; and the number of columns is fixed (contrary to a similar feature in MS Access for example). Commented Apr 19, 2013 at 17:00
  • So I think it might work then. The table has three columns. UserID, FieldNo, Value. I should be able to use the FieldNo as the third column. Commented Apr 19, 2013 at 17:02

2 Answers 2

2

You can use the PIVOT function to get the result. I used the row_number() function to generate the values that will be converted to columns.

If you know how many values you will have ahead of time, then you can hard-code the query:

select userid, Col1, Col2, Col3
from
(
  select userid, value,
    'Col'+cast(row_number() over(partition by userid 
                                  order by (select 1)) as varchar(10)) rn
  from yt
) d
pivot
(
  max(value)
  for rn in (Col1, Col2, Col3)
) piv;

See SQL Fiddle with Demo.

If you have an unknown number of values, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Col'+cast(row_number() over(partition by userid 
                                                                                    order by (select 1)) as varchar(10))) 
                    from yt
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT userid,' + @cols + ' 
             from 
             (
                select userid, value,
                  ''Col''+cast(row_number() over(partition by userid 
                                                order by (select 1)) as varchar(10)) rn
                from yt
            ) x
            pivot 
            (
                max(value)
                for rn in (' + @cols + ')
            ) p '

execute(@query);

See SQL Fiddle with Demo. Both give the result:

| USERID |   COL1 |         COL2 |      COL3 |
----------------------------------------------
|   8111 | 396285 | 812045789854 | Secretary |
Sign up to request clarification or add additional context in comments.

Comments

0

If you cannot or don't want to use PIVOT/UNPIVOT another option would be to join the columns one by one to the users:

DECLARE @Users TABLE(
    UserID int NOT NULL
)

INSERT INTO @Users (UserID) VALUES (1)
INSERT INTO @Users (UserID) VALUES (2)
INSERT INTO @Users (UserID) VALUES (3)

DECLARE @AnyTable TABLE(
    UserID int NOT NULL,
    FieldNo int NOT NULL,
    Value varchar(50) NULL
)

INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (1, 1, 'abc')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (1, 2, 'def')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (1, 3, 'ghi')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (2, 1, '123')
INSERT INTO @AnyTable (UserID, FieldNo, Value) VALUES (2, 3, '789')

SELECT u.UserID,
    col1.Value as Column1,
    col2.Value as Column2,
    col3.Value as Column3
FROM @Users u
LEFT JOIN @AnyTable col1
    ON col1.UserID = u.UserID
    AND col1.FieldNo = 1
LEFT JOIN @AnyTable col2
    ON col2.UserID = u.UserID
    AND col2.FieldNo = 2
LEFT JOIN @AnyTable col3
    ON col3.UserID = u.UserID
    AND col3.FieldNo = 3

The result would be:

UserID   Column1   Column2   Column3
 1        abc       def       ghi
 2        123       NULL      789
 3        NULL      NULL      NULL

Comments

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.