I have an audits table that has a created_at
column and need to show the number of audits for each year, but my client year from April to April.
For example, the result must show:
2011/2012 :10 // this is the range between April-2011 to April-2012
2012/2013 :5 // this is the range between April-2012 to April-2013
and so on...
答案 0 :(得分:1)
Since a GROUP BY
may contain an arbitrary expression, you might use some date manipulation to make each created_at
value behave as though it is a January-December year. You may do that by subtracting 3 months from it, so those after April will result in the current year, and those before April will result in the previous year. Wrapping that expression in YEAR()
will then group them on the calculated value.
GROUP BY YEAR(created_at - INTERVAL 3 MONTH)
For example, on or after April 1 returns the current year:
SELECT YEAR('2015-04-01' - INTERVAL 3 MONTH);
+---------------------------------------+
| YEAR('2015-04-01' - INTERVAL 3 MONTH) |
+---------------------------------------+
| 2015 |
+---------------------------------------+
And earlier returns the previous year for grouping:
SELECT YEAR('2015-03-01' - INTERVAL 3 MONTH);
+---------------------------------------+
| YEAR('2015-03-01' - INTERVAL 3 MONTH) |
+---------------------------------------+
| 2014 |
+---------------------------------------+
Here's a little sample: http://sqlfiddle.com/#!9/a6cca/1