I have a table that holds details of activities carried out by individuals - contents of this table is similar to the following:
| Person | Category | Activity | -------------------------------------- | Username1 | X | X1 | | Username1 | Y | Y1 | | Username1 | Z | Z1 |
I need a SQL query that can produce something like the following and any help would be appreciated:
| Person | Cat1 | Cat1_Act|Cat2 | Cat2_Act| Cat3 | Cat3_Act | --------------------------------------------------------------- | Username1 | X | X1 | Y | Y1 | Z | Z1 |
I understand reading through a number of posts that PIVOT can be used to achieve this but I have not been to find a solution close to what I need as most solutions are often to use values e.g 'X', 'Y', 'Z' (in my example table) as table headers but I want to ideally be able to specify name for the table headers holding the new columns (Hope this all makes sense and someone can help :-) )
There are several ways that you can get the desired result. If you have a limited number of values that you want to PIVOT into columns, then you can hard-code the query a few different ways.
Aggregate function with CASE:
See SQL Fiddle with Demo. By assigning a sequence or row_number to each category per user, you can use this row number to convert the rows into columns.
Static PIVOT:
If you want to apply the PIVOT function, then I would first suggest unpivoting the
category
andactivity
columns into multiple rows and then apply the pivot function.See SQL Fiddle with Demo
Dynamic PIVOT: Finally if you have an unknown number of values then you can use dynamic SQL to get the result:
See SQL Fiddle with Demo. All versions give a result:
this is a simple example