繁体   English   中英

MySQL:按日期范围分组

[英]MySQL: Grouping by date ranges

假设我们有一个包含id, title, status, expires_at, created_at列的Products表。

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

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-endactive

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

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

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)

我相信您希望给定星期内的活动产品的逻辑更像*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;

您可以使用函数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()不会影响同一周的年份。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM