postgresql OVER() Partition By Order By

写这篇文章的目的, 是通过一个测试案例,了解一下 pgsql的 OVER() Partition By Order By功能

一 、基本概念

Partition By :分组但不聚合
Order By :排序

二、实验说明

1)创建表并初试化数据

CREATE TABLE public.a_test
(
  a character varying(255),
  b character varying(255)
)

insert into a_test
values
(1, 1),
(2, 1),
(3, 1),
(4, 4),
(3, 3),
(5, 5)
(2, 2),
(3, 2)

2)查看初始化数据

select * from a_test;
postgresql OVER() Partition By Order By_第1张图片

3)OVER() Partition By Order By

select a, b,
count(1) OVER(PARTITION BY a ORDER BY a) AS count,
row_number() OVER(PARTITION BY a ORDER BY a) AS rownum
from a_test;
postgresql OVER() Partition By Order By_第2张图片

三、小结

  • count(1) OVER(PARTITION BY a ORDER BY a) AS count,是按a进行分组且组内按a进行升序,统计组内记录的条数
  • row_number() OVER(PARTITION BY a ORDER BY a) AS rownum,是按a进行分组且组内按a进行升序,返回组内行编号

你可能感兴趣的:(SQL,PARTITION,BY,ORDER,BY,count,row_number)