This is my table to track down the employees off days. This example is only for one person.
ID PID Year OffDays DayTypeNumber
------------------------------------------
1 1 2011 10 1
2 1 2011 5 2
3 1 2012 20 1
4 1 2012 3 2
I would like to write such a query that should only show one result for each year with additional column
Year OffDays(1) OffDays(2)
------------------------------------------
2011 10 5
2012 20 3
You can use the
PIVOTfunction for this:See SQL Fiddle with Demo
Result:
Or you can use an aggregate function with a
CASEstatement:See SQL Fiddle with Demo
If you only have two types that you are comparing, then you can use subqueries:
See SQL Fiddle with Demo
The above answers will work great, if you have a known number of values for
DayTypeNumber, but if those are unknown then you can use dynamic SQL to generate thePIVOT:See SQL Fiddle with Demo
All of these will produce the same results: