【问题标题】:cumulative sum of number of records grouped by week按周分组的记录数的累积总和
【发布时间】:2019-12-01 00:09:43
【问题描述】:

我有以下数据库架构

ID  creation_date
1      2019-06-03
2      2019-06-04
3      2019-06-04
4      2019-06-10
5      2019-06-11

我需要按周找出表组的总大小。我正在寻找的输出类似于

year   week number_of_records
2019    23      3
2019    24      5

我正在编写以下查询,它只给我每周创建的记录数

> select year(creation_date) as year, weekofyear(creation_date) as week,
> count(id) from input group by year, week;

我得到的输出是

year   week number_of_records
2019    23      3
2019    24      2

【问题讨论】:

    标签: mysql sql postgresql group-by aggregate


    【解决方案1】:

    你似乎想要一个累积的总和。您可以直接在聚合查询中使用窗口函数执行此操作:

    select year(creation_date) as year, weekofyear(creation_date) as week,
           count(*) as number_of_starts,
           sum(count(*)) over (order by min(creation_date)) as number_of_records
    from input
    group by year, week;
    

    【讨论】:

    【解决方案2】:

    看看窗口(或分析)函数。 与聚合函数不同,窗口函数保留结果行并促进与它们相关的操作。在over子句中使用order by时,按照指定的顺序从第一行到当前行开窗,正是你需要的。

    select year, week, sum(number_of_records) over (order by year, week)
    from (
      select year(creation_date) as year, weekofyear(creation_date) as week,
      count(id) as number_of_records
      from input group by year, week
    ) your_sql
    

    我猜你还需要重置每年的总和,我留给你做练习(提示:partition 子句)。

    【讨论】:

      【解决方案3】:

      对于 8.0 之前的版本...

      架构 (MySQL v5.7)

      CREATE TABLE my_table
      (ID SERIAL PRIMARY KEY
      ,creation_date DATE NOT NULL
      );
      
      INSERT INTO my_table VALUES
      (1    ,  '2019-06-03'),
      (2     , '2019-06-04'),
      (3     , '2019-06-04'),
      (4      ,'2019-06-10'),
      (5      ,'2019-06-11');
      

      查询 #1

      SELECT a.yearweek
      , @i:=@i+a.total running
      FROM
      (SELECT DATE_FORMAT(x.creation_date,'%x-%v') yearweek
      , COUNT(*) total
      FROM my_table x
      GROUP BY yearweek
      )a
      JOIN (SELECT @i:=0) vars
      ORDER BY a.yearweek;
      
      | yearweek | running |
      | -------- | ------- |
      | 2019-23  | 3       |
      | 2019-24  | 5       |
      
      ---
      

      View on DB Fiddle

      【讨论】:

        猜你喜欢
        • 2015-09-11
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 2014-07-13
        • 2021-06-18
        • 2018-05-30
        • 2020-12-23
        • 1970-01-01
        相关资源
        最近更新 更多