Edited:
One column per result:
If you try to combine multiple Attributes with the same UserID it would be something like this:
Short query (one UserID):
declare @concattedtext varchar(1000)
SELECT @concattedtext=coalesce(@concattedtext + '|', '') + Value
FROM #users WHERE UserID=1
SELECT @concattedtext
RESULT with your example data:
1 | Marius | Fubar
Full query (all UserID's)
-- Your source table
CREATE Table #users (UserID int, Attribute varchar(50), Value varchar(50))
-- some entries
INSERT into #users (UserID, Attribute, Value)
VALUES (1, 'Test1', 'attr1')
INSERT into #users (UserID, Attribute, Value)
VALUES (1, 'Test2', 'attr2')
INSERT into #users (UserID, Attribute, Value)
VALUES (1, 'Test3', 'attr3')
INSERT into #users (UserID, Attribute, Value)
VALUES (2, 'Test4', 'attr4')
-- ids table variable (for distinct UserID's)
DECLARE @ids TABLE
(
rownum int IDENTITY (1, 1) Primary key NOT NULL,
UserID int
)
-- Output table variable
DECLARE @out TABLE
(
rownum int IDENTITY (1, 1) Primary key NOT NULL,
UserID int,
ConcatText varchar(1000)
)
-- get distinct id's
INSERT INTO @ids(UserID)
SELECT DISTINCT(UserID) FROM #users
-- Foreach vars
declare @RowCnt int
declare @MaxRows int
select @RowCnt = 1
select @MaxRows=count(*) from @ids
-- UserID
declare @id int
declare @concattedtext varchar(1000)
-- process each id
while @RowCnt <= @MaxRows
begin
SET @id = 0
SELECT @id=UserID
FROM @ids WHERE rownum=@RowCnt
SET @concattedtext = CONVERT(nvarchar(50), @id)
FROM @ids WHERE rownum=@RowCnt
SELECT @concattedtext=coalesce(@concattedtext + '|', '') + Value
FROM #users WHERE UserID=@id
INSERT INTO @out(UserID, ConcatText)
VALUES (@id, @concattedtext)
-- next UserID
Select @RowCnt = @RowCnt + 1
end
SELECT * FROM @out
DROP TABLE #users
Result:
rownum|UserID|ConcatTex
1 | 1 |1|attr1|attr2|attr3
2 | 2 |2|attr4
DROP TABLE #users
You might need a sort field to get your parameters in your requested order.
Multiple columns
Your data needs to have an equal count of attributes if you like to get a table with multiple columns. And you still need to take care about the ordering.
In this case a hardcoded query with a group by would be your choice.