簡體   English   中英

聚合時Postgres填寫空數據

[英]Postgres Fill In Empty Data When Aggregating

在Postgres中,我匯總了總計金額,分開了幾天,然后將該數據轉儲到圖表中。 查詢示例如下所示:

SELECT 
EXTRACT(YEAR FROM post_created_date) as report_year, EXTRACT(WEEK FROM post_created_date) AS regweek, COUNT(post_id) as post_count 
FROM TableA 
GROUP BY report_year, regweek

這可以正常工作,但是在某些日子沒有數據,給圖表留下了空白

1/14  -  5
1/15  -  7
1/18  -  4

如何包含該日期沒有事件報告0的日期?

為此,您需要使用left outer join 這個想法是創建年份和星期的所有組合,然后加入您的查詢。 在Postgres中,使用generate_series()非常簡單。 就像是:

select yw.yr, yw.wk, coalesce(r.post_count, 0) as post_count
from (select distinct EXTRACT(YEAR FROM post_created_date) as yr,
             generate_series(1, 52) as wk
      from TableA
     ) yw left outer join
     (SELECT EXTRACT(YEAR FROM post_created_date) as report_year,
             EXTRACT(WEEK FROM post_created_date) AS regweek, COUNT(post_id) as post_count 
      FROM TableA 
      GROUP BY report_year, regweek
     ) r
     on yw.yr = report_year and yw.wk = regweek;

暫無
暫無

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

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