AndrewMcLagan
AndrewMcLagan

Reputation: 13987

MySQL: Grouping by date ranges

Say we have a table of Products with the columns id, title, status, expires_at, created_at.

I can get the values for single week by specifying all the parameters:

SELECT
    count(id)
FROM 
    products
WHERE
    status = 'APPROVED' AND
    expires_at >= '2018-09-10 09:00:00' AND
    created_at <= '2018-09-10 09:00:00' AND
    deleted_at IS NULL;

How could we run a query that groups the products by weeks of the year 1-52 -- WHERE each week shows Products that were not expired: created_at <= week-end AND expires_at <= week-end or active:

Active_Products | Week_Of_Year 
----------------|---------------
274             | 2018-01
----------------|---------------
1011            | 2018-02
----------------|---------------
180             | 2018-03
----------------|---------------
990             | 2018-04
----------------|---------------
765             | 2018-05

I have updated this question with an SQL fiddle: http://sqlfiddle.com/#!9/e4830b/4

Upvotes: 0

Views: 146

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1271003

I believe the logic you want for the active products in a given week is more like *created_at* >= week-start AND expires_at < week-end.

If you have products created during all weeks, then you can use a correlated subquery:

select week_of_year,
       (select count(*)
        from products t2
        where yearweek(t2.created_at) >= w.week_of_year and
              yearweek(t2.expires_at) < w.week_of_year
       ) as num_actives
from (select distinct yearweek(created_at) as week_of_year
      from products
     ) w;

Upvotes: 1

F.Igor
F.Igor

Reputation: 4410

You can use the function YEARWEEK(date) (https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_yearweek) to show the week number in a reada readable way including the year (yyyymm).

SELECT 
count(id) as active_products, YEARWEEK(expires_at)
FROM products
GROUP BY YEARWEEK(expires_at)

Using WEEK() will not make difference between years in the same week.

Upvotes: 0

Fahmi
Fahmi

Reputation: 37483

Try below query by calculating week start date and end date

select week(expires_at),count(id) as active_products
from product
where expires_at>SUBDATE(expires_at, weekday(expires_at)) and expires_at<DATE(expires_at + INTERVAL (6 - WEEKDAY(expires_at)) DAY)
group by week(expires_at)

Upvotes: 1

Related Questions