I have a table:
+----+-------+------+
| id | times | year |
+----+-------+------+
| 5 | 2 | 2008 |
| 6 | 76 | 2008 |
| 2 | 43 | 2009 |
| 4 | 5 | 2009 |
| 1 | 3 | 2010 |
| 9 | 6 | 2010 |
| 7 | 444 | 2011 |
| 8 | 3 | 2011 |
| 3 | 65 | 2012 |
+----+-------+------+
I would like to create a pivot out of this table which buckets times per year :
+--------+------+------+------+------+------+
| | 2008 | 2009 | 2010 | 2011 | 2012 |
+--------+------+------+------+------+------+
| 0 | | | | | |
| 1-30 | 1 | 1 | 2 | 1 | |
| 31-60 | | 1 | | | |
| 61-90 | 1 | | | | 1 |
| 91-120 | | | | | |
| 121+ | | | | 1 | |
+--------+------+------+------+------+------+
how do i start to tackle this challenge with sql? thank you so much for your guidance.
You can use the sql server
PIVOTfunction for this. If you know the all of the values for the years as well as the buckets then you can hard-code the query:See SQL Fiddle with Demo
If you don’t have access to the
PIVOTfunction then you can use an aggregate function with aCASE:See SQL Fiddle with Demo
If you need all of the buckets to be listed, then you will want to have the bucket ranges stored in either a table or using a
CTEquery, then you can use the following:See SQL Fiddle with Demo
Result:
The above will work great if you have a known number of values (years) that you need to transpose. If you have an unknown number then you will want to implement dynamic sql, similar to this:
See SQL Fiddle with Demo
The result will be the same for both the static (hard-coded) version and the dynamic version.