mysql - 按周分组的记录数的累计总和

标签 mysql sql postgresql group-by aggregate

我有以下数据库模式

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

最佳答案

看看窗口(或分析)函数。 与聚合函数不同,窗口函数保留结果行并促进与它们相关的操作。当在 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 子句)。

关于mysql - 按周分组的记录数的累计总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155799/

相关文章:

php - 快速远程 mysql 连接的最佳方法/设置是什么?

mysql - 数据库设计 : users and guests

sql - 优化以通配符开头的 LIKE 表达式

sql - 如何删除 postgresql/Rails 连接结果集中的重复项

sql - Mariadb 唯一约束错误(重复条目),两个记录有一个空间差异

PostgreSQL 说明

mysql - Wamp-命令行 "mysqld"不起作用

mysql - 无法在 debian 上安装 libmysql++-dev

python - 在 psycopg2 中打开 postgres 连接导致 python 崩溃

java - 在Java中获取没有时区的时间