I am very new to SQL.
I have a table like this:
ID | TeamID | UserID | ElementID | PhaseID | Effort
-----------------------------------------------------
1 | 1 | 1 | 3 | 5 | 6.74
2 | 1 | 1 | 3 | 6 | 8.25
3 | 1 | 1 | 4 | 1 | 2.23
4 | 1 | 1 | 4 | 5 | 6.8
5 | 1 | 1 | 4 | 6 | 1.5
And I was told to get data like this
ElementID | PhaseID1 | PhaseID5 | PhaseID6
--------------------------------------------
3 | NULL | 6.74 | 8.25
4 | 2.23 | 6.8 | 1.5
I understand I need to use PIVOT function. But can't understand it clearly. It would be great help if somebody can explain it in above case.(or any alternatives if any)
These are the very basic pivot example kindly go through that.
SQL SERVER – PIVOT and UNPIVOT Table Examples
Example from above link for the product table:
renders:
Similar examples can be found in the blog post Pivot tables in SQL Server. A simple sample
A
PIVOT
used to rotate the data from one column into multiple columns.For your example here is a STATIC Pivot meaning you hard code the columns that you want to rotate:
Here is a SQL Demo with a working version.
This can also be done through a dynamic PIVOT where you create the list of columns dynamically and perform the PIVOT.
The results for both:
To set Compatibility error
use this before using pivot function
I was new to this and I create a nice post about it... My problem was understanding how to apply aggregation correctly and here is my post: http://jaider.net/posts/1176-pivot-in-sql-server-correct-aggregated-results/
In @bluefeet solution, It's important to mention that
elementid
is the key column of your "invisible"Group By
. Additionally, you can replaceelementid
or add more columns such asuserid
.