【问题标题】:Cumulative count over weeks in SQLSQL 中数周内的累积计数
【发布时间】:2021-09-01 07:57:39
【问题描述】:

我有一个项目表,其所有者 ID 引用用户表中的用户。

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

对于这个表:

id owner created
1 xxxxx '2021-01-01'
2 xxxxx '2021-01-01'
3 xxxxx '2021-01-09'

我想得到:

count owner week
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

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql count cumulative-sum


【解决方案1】:

我对你的问题有点困惑:

  • 您有一个从 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。

【讨论】:

    【解决方案2】:

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

    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 列中的值进行累积和。

    【讨论】:

      【解决方案3】:

      从 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多