postgresql 如何使用generate_series获取周间隔内的值的总和

snz8szmq  于 2023-01-08  发布在  PostgreSQL
关注(0)|答案(1)|浏览(108)

我在每周使用generate_series时遇到了麻烦。这里有两个例子,一个是每月,它按预期工作。它返回每个月和facts.sends值的总和。我试图在每周使用generate_series时做同样的事情,但是值没有正确相加。
每月间隔(工作):https://www.db-fiddle.com/f/a9SbDBpa9SMGxM3bk8fMAD/0
每周间隔(不工作):https://www.db-fiddle.com/f/tNxRbCxvgwswoaN7esDk5w/2

xdnvmnnf

xdnvmnnf1#

应生成从星期一开始的系列。

WITH range_values AS (
  SELECT date_trunc('week', min(fact_date)) as minval,
         date_trunc('week', max(fact_date)) as maxval
  FROM facts),

week_range AS (
  SELECT generate_series(date_trunc('week', '2022-05-01'::date), now(), '1 week') as week
  FROM range_values
),

grouped_facts AS (
  SELECT date_trunc('week', fact_date) as week,
    sends
  FROM facts
  WHERE
    fact_date >= '2022-05-20'
)

SELECT week_range.week,
       COALESCE(sum(sends)::integer, 0) AS total_sends
FROM week_range
LEFT OUTER JOIN grouped_facts on week_range.week = grouped_facts.week
GROUP BY 1
ORDER BY 1;

DB Fiddle.

相关问题