Postgres-sql:
我无法找到一个资源来帮助我理解如何正确使用带有/内部窗口函数的聚合,以及如何正确地使用范围/行frame_clause。我在网上查阅了一些资源,比如:https://www.compose.com/articles/metrics-maven-window-frames-in-postgresql/
(我真的很喜欢这篇文章,它解决了一些疑问)
正确使用聚合的
添加更多的列
例如:这里的问题:https://pgexercises.com/questions/aggregates/fachours4.html
select facid, total from
(select facid, sum(slots) total, RANK() OVER (order by sum(slots) desc) pos
from cd.bookings
group by facid
) A
where pos = 1我编写了这个查询,它工作正常。但是对于这个:https://pgexercises.com/questions/aggregates/rollingavg.html,我写了这个查询:
select starttime::date, sum(slots * case when memid=0 then guestcost
else membercost end) over (order by starttime::date asc
range BETWEEN INTERVAL '14 day'
PRECEDING AND
CURRENT ROW)::decimal/15 revenue
from cd.bookings B inner join cd.facilities F
on B.facid = F.facid
where starttime >= '2012-08-01' and starttime <= '2012-08-31'
group by starttime::date, slots, memid, guestcost, membercost
order by starttime::date当它们是平均计算的一部分时,它要求我在组中添加插槽、memid、访客成本、成员成本。我还没有正确地解决这个问题。
UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING,但是对于这里的last_value()计算,需要指定以下子句:SELECT
product_name,
group_name,
price,
LAST_VALUE (price) OVER (
PARTITION BY group_name
ORDER BY
price RANGE BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) AS highest_price_per_group
FROM
products
INNER JOIN product_groups USING (group_id);(本例取自此处:https://www.postgresqltutorial.com/postgresql-window-function/ -对不起,无法选择页面中要链接的确切区域)
vs
SELECT
RANK () OVER (
ORDER BY price
) rank_number
FROM
sales;->这个排序正确,不需要指定BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING子句。
发布于 2022-03-28 14:01:45
https://momjian.us/main/writings/pgsql/window.pdf (幻灯片35和幻灯片36)
https://modern-sql.com/caniuse/over_range_between_(numeric)
我希望下面的图片能帮助你理解行和范围之间的区别。

https://stackoverflow.com/questions/71632040
复制相似问题