首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解窗口函数

理解窗口函数
EN

Stack Overflow用户
提问于 2022-03-26 21:42:01
回答 1查看 146关注 0票数 0

Postgres-sql:

我无法找到一个资源来帮助我理解如何正确使用带有/内部窗口函数的聚合,以及如何正确地使用范围/行frame_clause。我在网上查阅了一些资源,比如:https://www.compose.com/articles/metrics-maven-window-frames-in-postgresql/

(我真的很喜欢这篇文章,它解决了一些疑问)

正确使用聚合的

  1. 与/内窗口函数SUM(.)有时在我最不期望多行的时候产生多个行,或者让我向

添加更多的列

例如:这里的问题:https://pgexercises.com/questions/aggregates/fachours4.html

代码语言:javascript
复制
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,我写了这个查询:

代码语言:javascript
复制
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、访客成本、成员成本。我还没有正确地解决这个问题。

  1. 不同的窗口函数如何对范围/行进行操作?例如,秩()似乎产生了正确的结果,而没有为其指定框架子句UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING,但是对于这里的last_value()计算,需要指定以下子句:

代码语言:javascript
复制
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

代码语言:javascript
复制
SELECT
    RANK () OVER ( 
        ORDER BY price
    ) rank_number 
FROM
    sales;

->这个排序正确,不需要指定BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING子句。

EN

回答 1

Stack Overflow用户

发布于 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)

我希望下面的图片能帮助你理解行和范围之间的区别。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71632040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档