给出团队的数据集
id | team_name | points
1 | A | 10
2 | B | 20
3 | C | 30
4 | D | 40
5 | E | 50
我可以将此查询与窗口函数结合使用以获取前3名球队的平均值
with top_3 as(
select *
from teams
order by points desc
limit 3
)
select *, avg(points) over() as top3_average
from top_3
是否可以仅在数据集中的前3行使用窗口函数?
我尝试过,但是那肯定行不通。
OVER(... limit 3)
这是工作中的sqlfiddle
请明确说明,我知道可以使用像这样的子查询来做到这一点。我对学习是否可以使用窗口函数
更感兴趣select *, avg(points) over() as top3_average
from teams
where id in
(select id
from teams
order by points desc
limit 3)
答案 0 :(得分:1)
可以使用row_number()
窗口功能
with top_3 as(
select * ,row_number() over(order by points desc) rn
from teams
) select * form top_3 where rn<=3
答案 1 :(得分:1)
不,不是。您不能轻易指定仅包含前三行的FRAME。您可以在第一行中获得平均值,然后在其他任何地方放置空值,但这似乎是一个糟糕的主意:
select *,
avg(points) OVER (ORDER BY points desc ROWS BETWEEN UNBOUNDED PRECEDING AND 2 FOLLOWING)
* CASE WHEN row_number() OVER (ORDER BY points desc) = 1 THEN 1 ELSE null END
FROM teams;
id | team_name | points | ?column?
----+-----------+--------+---------------------
6 | F | 60 | 50.0000000000000000
5 | E | 50 |
4 | D | 40 |
3 | C | 30 |
2 | B | 20 |
1 | A | 10 |
(6 rows)