J
J
jj_killer2012-07-21 06:45:18
MySQL
jj_killer, 2012-07-21 06:45:18

GROUP BY weeks; How to display a range?

SELECT
  DATE_FORMAT(`start_date`, '%x-%v') weeks,
  COUNT(*)
FROM `events` GROUP BY weeks;


Outputs in the format [2011-05, 34], i.e. year, week number and number of events. You need to output something like [2011-01-31 - 2011-02-06, 34].

There is an option to process this on the application side, but I would still like to leave it to SQL.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Placido, 2012-07-21
@jj_killer

This option:

SELECT
  DATE_FORMAT(`start_date`, '%x-%v') weeks,
  COUNT(*), DATE_ADD(`start_date`, INTERVAL(2-DAYOFWEEK(`start_date`)) DAY) first_date,
    DATE_ADD(`start_date`, INTERVAL(8-DAYOFWEEK(`start_date`)) DAY) last_date
FROM `events` GROUP BY weeks;

A
Alexey Skahin, 2012-07-21
@pihel

So it won't work?

SELECT
  DATE_FORMAT(`start_date`, '%x-%v') weeks,
  MAX(`start_date`), MIN(`start_date`)
  COUNT(*)
FROM `events` GROUP BY weeks;

E
EndUser, 2012-07-21
@EndUser

Group with lines - IMHO will be a bit slow.
If in a locale, I would time it like this: form a week string, a numerical week number, a counter; would group by the numerical number of the week, would select two columns in the application.
If the load on the network is too large due to the numerical week number, I would leave it as you have, except that the line format would be changed to the one you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question