SQLTeam.com | Weblogs | Forums

Return one attribute in two columns

I´ve got a table that looks like this:

UserID ParameterName ParamaterData
1 Department 2nd floor
1 Category Sports
1 Salary 5.000$
2 Department 1st floor
2 Category Fashion
2 Phonenumber 123456
3 Salary 4.500$
3 Phonenumer 789321

There´re a numerous of different "attributes" in the column ParName and every user doesn´t have to have all or any attributes for that matter.

Now, I´d like to make a query that returns UserID, Department and Category.
So the result should look like this:

UserID Department Category
1 2nd floor Sports
2 1st floor Fashion

I´m not interested in Salary nor Phonenumber, just every users department and category.

How do I return the single column ParamaterData into two columns based on their paramater name?


SELECT UserID,
    MAX(CASE WHEN ParameterName = 'Department' THEN ParamaterData END) AS Department,
    MAX(CASE WHEN ParameterName = 'Category' THEN ParamaterData END) AS Category
FROM dbo.table_name
GROUP BY UserID
ORDER BY UserID
1 Like