Question

I am looking to do something like get all rows from table

where date >='2012-05-05' and date<='2012-07-20'

I want MySQL to return "group by" rows mont wise incremented from

2012-05-05 to 2012-06-05(incerement 1 month)
2012-06-06 to 2012-07-06(increment 1` month)
and remaining 2012-07-07 to 2012-07-20 (group the remaining 14 days)

how can i write my query to achieve the same?

Thank you...

Was it helpful?

Solution

Try this solution:

You can GROUP BY the number of months elapsed from your parameter minimum (2012-05-05) + 1 to the date in each row via the TIMESTAMPDIFF() function:

GROUP BY TIMESTAMPDIFF(MONTH, '2012-05-05' + INTERVAL 1 DAY, date)

The reason why we +1 day to your minimum parameter is because:

  • 2012-05-05 to 2012-06-04 is 0 months, but...
  • 2012-05-05 to 2012-06-05 is 1 month

^ Because of that, the row(s) on 2012-06-05 would be grouped separately from dates that had 0 months elapsed when we actually want it grouped WITH them.


Edit: I was fiddling around with this solution not only grouping by the month intervals, but also displaying the from and to dates of each interval.

Check it out:

SQLFiddle Demo

OTHER TIPS

You could use the case expression and then group by on the result of case.

SELECT 
  CASE 
    WHEN where date >='2012-05-05' and date<='2012-06-05' THEN 1 
    WHEN where date >='2012-06-06' and date<='2012-07-06' THEN 2 
    ELSE 3 
  END AS period, COUNT(*)
FROM your_table
GROUP BY period

Hope this help, I assumed the date range is dynamic like this :

2012-01-01 to 2012-02-01
2012-02-02 to 2012-03-02
2012-03-03 to 2012-04-03
2012-04-04 to 2012-05-04
2012-05-05 to 2012-06-05
...

So, I can group it using :

SELECT *, IF(day(date)>=month(date), month(date), month(date)-1) as PERIOD 
FROM your_tablename 
GROUP BY PERIOD;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top