簡體   English   中英

SQL 中數周的累積計數

[英]Cumulative count over weeks in SQL

我有一個項目表,所有者 ID 引用用戶表中的用戶。

我想顯示每周(按周分組)每個用戶在該周創建的項目數 + 之前創建的所有項目 - 累積計數。

對於此表:

ID 所有者 創建
1 xxxxxx '2021-01-01'
2 xxxxxx '2021-01-01'
3 xxxxxx '2021-01-09'

我想得到:

數數 所有者 星期
2 xxxxxx '2021-01-01' - '2021-01-07'
3 xxxxxx '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

我對您的查詢有點困惑:

  • 您有一個從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。

從 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 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 列中的值進行累計總和。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM