PostgreSQL – CUME_DIST函数
在PostgreSQL 中, CUME_DIST ()函数用于查询一组给定值中某个值的相对位置。
Syntax:
CUME_DIST() OVER (
[PARTITION BY partition_expression, ... ]
ORDER BY sorting_expression [ASC | DESC], ...
)
我们来分析一下上面的语法:
- PARTITION BY 是一个可选子句,它将行划分为应用该函数的多个分区。如果未设置,postgreSQL 会将整个结果集视为单个分区。
- ORDER BY子句排序在施加函数的每个分区的行。
返回值:
所述CUME_DIST()函数返回0和1之间的双精度值:
0 < CUME_DIST() <= 1
示例 1:
首先,创建一个名为sales_stats的表 存储员工的销售收入:
CREATE TABLE sales_stats(
name VARCHAR(100) NOT NULL,
year SMALLINT NOT NULL CHECK (year > 0),
amount DECIMAL(10, 2) CHECK (amount >= 0),
PRIMARY KEY (name, year)
);
其次,在sales_stats 中插入一些行 桌子:
INSERT INTO
sales_stats(name, year, amount)
VALUES
('Raju kumar', 2018, 120000),
('Alibaba', 2018, 110000),
('Gabbar Singh', 2018, 150000),
('Kadar Khan', 2018, 30000),
('Amrish Puri', 2018, 200000),
('Raju kumar', 2019, 150000),
('Alibaba', 2019, 130000),
('Gabbar Singh', 2019, 180000),
('Kadar Khan', 2019, 25000),
('Amrish Puri', 2019, 270000);
以下查询返回 2018 年每位销售员工的销售额百分比:
SELECT
name,
year,
amount,
CUME_DIST() OVER (
ORDER BY amount
)
FROM
sales_stats
WHERE
year = 2018;
输出:
示例 2:
以下查询使用CUME_DIST ()函数计算 2018 年和 2019 年每个销售员工的销售百分位数:
SELECT
name,
year,
amount,
CUME_DIST() OVER (
PARTITION BY year
ORDER BY amount
)
FROM
sales_stats;
输出: