MySQL:按日期范围分组

时间:2018-09-10 07:40:54

标签: php mysql sql group-by

假设我们有一个Products表,其中有id, title, status, expires_at, created_at列。

我可以通过指定所有参数来获取一周的值:

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;

我们如何运行按年份 1-52 对产品进行分组的查询-每周在哪里显示未过期的产品:created_at <= week-end AND expires_at <= week-end有效

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

我已使用SQL小提琴更新了此问题:http://sqlfiddle.com/#!9/e4830b/4

3 个答案:

答案 0 :(得分:1)

通过计算星期开始日期和结束日期尝试以下查询

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)

答案 1 :(得分:1)

我相信您希望给定一周内的有效产品的逻辑更像*created_at* >= week-start AND expires_at < week-end

如果您在整周内都创建了产品,则可以使用相关的子查询:

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;

答案 2 :(得分:0)

您可以使用函数YEARWEEK(date)https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_yearweek)以包括年份(yyyymm)可读的方式显示星期数。

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

使用WEEK()不会在同一周的年份之间产生差异。