当前位置: 首页 > article >正文

postgreSQL window function高级用法

正常使用:相当于对每个row做一次子查询

SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary;

order by 区别window frame and partition

没有order by, window function是对整个partition起作用, partition是over语句制定的
有了order by,那window function就是对window frame起作用,window frame就是整个partition先按照order by排序,然后到当前row为止的所有数据。
There is another important concept associated with window functions: for each row, there is a set of rows within its partition called its window frame. Some window functions act only on the rows of the window frame, rather than of the whole partition. By default, if ORDER BY is supplied then the frame consists of all rows from the start of the partition up through the current row, plus any following rows that are equal to the current row according to the ORDER BY clause. When ORDER BY is omitted the default frame consists of all rows in the partition. [5] Here is an example using sum:

SELECT salary, sum(salary) OVER () FROM empsalary;
 salary |  sum  
--------+-------
   5200 | 47100
   5000 | 47100
   3500 | 47100
   4800 | 47100
   3900 | 47100
   4200 | 47100
   4500 | 47100
   4800 | 47100
   6000 | 47100
   5200 | 47100
(10 rows)

没有order by, sum的结果是一样的,因为只有一个partition。

SELECT salary, sum(salary) OVER (ORDER BY salary) FROM empsalary;
 salary |  sum  
--------+-------
   3500 |  3500
   3900 |  7400
   4200 | 11600
   4500 | 16100
   4800 | 25700
   4800 | 25700
   5000 | 30700
   5200 | 41100
   5200 | 41100
   6000 | 47100
(10 rows)

有了order by,每次只计算不断增长的window frame

可复用的window表达式

SELECT sum(salary) OVER w, avg(salary) OVER w
  FROM empsalary
  WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);

window function执行顺序

window function是在where, group执行完以后才执行的,所以不可以用在where, group语句里面,只能用在select,order by子语句。
Window functions are permitted only in the SELECT list and the ORDER BY clause of the query. They are forbidden elsewhere, such as in GROUP BY, HAVING and WHERE clauses. This is because they logically execute after the processing of those clauses. Also, window functions execute after non-window aggregate functions. This means it is valid to include an aggregate function call in the arguments of a window function, but not vice versa.


http://www.kler.cn/a/580616.html

相关文章:

  • Facebook 隐私保护技术的发展与未来趋势
  • 探索在生成扩散模型中基于RAG增强生成的实现与未来
  • 初次体验Tauri和Sycamore(3)通道实现
  • 自然语言处理:无监督朴素贝叶斯模型
  • <3D建模>.max文件转换为.fbx文件
  • Ubuntu 24.04.2 允许 root 登录桌面、 ssh 远程、允许 Ubuntu 客户机与主机拖拽传递文件
  • MyBatis SqlSession 的作用,以及如何使用 SqlSession 执行 SQL 语句
  • Compose 实践与探索一 —— 关键知识与概念详解
  • 应急响应--流量分析
  • anolis8.9-k8s1.32-node-二进制部署
  • SSE vs WebSocket:AI 驱动的实时通信抉择
  • thinkphp+mysql+cast解决text类型字段的文本型数字排序错误的方法 - 数据库文本字段排序ASC、DESC的失效问题
  • leetcode:单词距离
  • 美畅物联丨P2P系列之STUN服务器:助力网络穿透
  • 使用服务器搭建无门槛ChatGPT WEB应用LobeChat
  • 做到哪一步才算精通SQL
  • Linux网络之数据链路层协议
  • MySQL自动化配置工具开发
  • 图论的基础知识:平凡图、简单图、连通图、平面图、完全图、对偶图、同构图
  • 【Bert系列模型】