【问题标题】:MySQL: Grouping by date rangesMySQL:按日期范围分组
【发布时间】:2019-02-14 14:44:12
【问题描述】:

假设我们有一个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 -- WHERE 每周显示未过期的产品:created_at &lt;= week-end AND expires_at &lt;= week-end活动 em>:

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

【问题讨论】:

  • 您能否提供一些示例数据并期待结果
  • 如果您花时间阅读问题的完整规范,这不是重复的。

标签: php mysql sql group-by


【解决方案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)

【讨论】:

    【解决方案2】:

    我相信你想要的给定一周内活跃产品的逻辑更像*created_at* &gt;= week-start AND expires_at &lt; 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;
    

    【讨论】:

    • 啊,我觉得这真的很接近。虽然很难理解所有不同的表名是什么?原始Products 表在哪里适合该查询?
    • @AndrewMcLagan 。 . . t 是我用于通用表名的简写。现在您已经指定了表格,我已经更新了答案。
    • 无法使这个查询工作。我创建了一个 SQLFiddle sqlfiddle.com/#!9/e4830b/4
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 2021-11-16
      • 2016-04-15
      相关资源
      最近更新 更多