代码之家  ›  专栏  ›  技术社区  ›  AndrewMcLagan

MySQL:按日期范围分组

  •  0
  • AndrewMcLagan  · 技术社区  · 6 年前

    假设我们有一张桌子 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 fiddle更新了这个问题: http://sqlfiddle.com/#!9/e4830b/4

    3 回复  |  直到 6 年前
        1
  •  1
  •   Fahmi    6 年前

    通过计算周的开始日期和结束日期来尝试下面的查询

    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)
    
        2
  •  1
  •   Gordon Linoff    6 年前

    *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;
    
        3
  •  0
  •   F.Igor    6 年前

    YEARWEEK(date) ( https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_yearweek 包括当年

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

    使用 WEEK() 不会影响同一周内的年份。