SQL 周内的累计计数

Cumulative count over weeks in SQL

我有 table 项的所有者 ID 引用来自用户 table 的用户。

我想显示每周(按周分组)每个用户在该周创建了多少项目 + 之前创建的所有项目 - 累计计数。

为此table:

id 所有者 已创建
1 xxxxx '2021-01-01'
2 xxxxx '2021-01-01'
3 xxxxx '2021-01-09'

我想得到:

计数 所有者
2 xxxxx '2021-01-01' - '2021-01-07'
3 xxxxx '2021-01-08' - '2021-01-14'

这是非累计计数的代码。我怎样才能把它改成累积的?

select
    count(*),
    uu.id,
    date_trunc('week', CAST(it.created AS timestamp)) as week
from items it
    left join users uu on uu.id = item.owner_id
group by uu.id, week

从 GROUP BY 子句和 SELECT 列表中删除用户 ID:

select
  count(*),
  date_trunc('week', CAST(it.created AS timestamp)) as week
from items it
  left join users uu on uu.id = item.owner_id
group by week

这是一个可运行的小示例(SQL 服务器),也许它会有所帮助:

create table #temp (week int, cnt int)

select * from #temp

insert into #temp select 1,2
insert into #temp select 1,1
insert into #temp select 2,3
insert into #temp select 3,3

select 
week, 
sum(count(*)) over (order by week) as runningCnt
from #temp
group by week

输出为:
周 - runningCnt
1 - 3
2 - 5
3 - 6

所以第一周有 3 个,下周又来了 2 个,上周又来了一个。

您还可以对 cnt 列中的值进行累加。

我对你的查询有点困惑:

  • 您有一个从 itemsusersleft join,就好像您希望某些项目没有有效的用户 ID。
  • 您在 select 中使用 u.id,但那将是 NULL,没有匹配项。

我建议:

select it.owner_id,
       date_trunc('week', it.created::timestamp) as week_start,
       date_trunc('week', it.created::timestamp) + interval '6 day' as week_end,
       count(*) as this_week,
       sum(count(*)) over (partition by uu.id order by min(timestamp)) as running_count
from items it
group by it.owner_id, week_start;

这使用 Postgres 语法,因为您的代码看起来像 Postgres。