gpt4 book ai didi

sql - 在窗口函数中计算运行总和

转载 作者:行者123 更新时间:2023-11-29 14:19:43 26 4
gpt4 key购买 nike

我在 Redshift(使用 Postgres 8)中遇到这个运行总和问题:

select extract(month from registration_time) as month
, extract(week from registration_time)%4+1 as week
, extract(day from registration_time) as day
, count(*) as count_of_users_registered
, sum(count(*)) over (ORDER BY (1,2,3))
from loyalty.v_user
group by 1,2,3
order by 1,2,3
;

我得到的错误是:

ERROR: 42601: Aggregate window functions with an ORDER BY clause require a frame clause

最佳答案

可以在同一查询级别上对聚合函数的结果运行窗口函数。在这种情况下使用子查询要简单得多:

SELECT *, sum(count_registered_users) OVER (ORDER BY month, week, day) AS running_sum
FROM (
SELECT extract(month FROM registration_time)::int AS month
, extract(week FROM registration_time)::int%4+1 AS week
, extract(day FROM registration_time)::int AS day
, count(*) AS count_registered_users
FROM loyalty.v_user
GROUP BY 1, 2, 3
ORDER BY 1, 2, 3
) sub;

我还修复了表达式计算 week 的语法。 extract() 返回 double ,但模运算符% 不接受 double 数字。我将所有三个都转换为 integer

@a_horse commented ,您不能在窗口函数的 ORDER BY 子句中使用位置引用(与查询的 ORDER BY 子句不同)。

但是,您不能在此查询中使用 over (order by registration_time),因为您是按 monthweekregistration_time 既未聚合,也未按要求包含在 GROUP BY 子句中。在查询评估的那个阶段,您无法再访问该列。

可以重复 ORDER BY 子句中前三个 SELECT 项的表达式以使其工作:

SELECT extract(month FROM registration_time)::int     AS month
, extract(week FROM registration_time)::int%4+1 AS week
, extract(day FROM registration_time)::int AS day
, count(*) AS count_registered_users
, sum(count(*)) OVER (ORDER BY
extract(month FROM registration_time)::int
, extract(week FROM registration_time)::int%4+1
, extract(day FROM registration_time)::int) AS running_sum
FROM loyalty.v_user
GROUP BY 1, 2, 3
ORDER BY 1, 2, 3;

但这似乎相当嘈杂。 (不过性能会很好。)

旁白:我确实想知道 week%4+1 背后的目的……整个查询可能更简单。

相关:

关于sql - 在窗口函数中计算运行总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33574053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com