- Mastering PostgreSQL 10
- Hans Jürgen Sch?nig
- 286字
- 2021-06-30 19:04:02
Utilizing windowing functions and analytics
Now we have discussed ordered sets, it is time to take a look at windowing functions. Aggregates follow a fairly simple principle: take many rows and turn them into fewer, aggregated rows. A windowing function is different. It compares the current row with all rows in the group. The number of rows returned does not change.
Here is an example:
test=# SELECT avg(production) FROM t_oil; avg ----------- 2607.5139 (1 row)
test=# SELECT country, year, production,
consumption, avg(production) OVER ()
FROM t_oil
LIMIT 4; country | year | production | consumption | avg ---------+-------+------------+-------------+---------- USA | 1965 | 9014 | 11522 | 2607.5139 USA | 1966 | 9579 | 12100 | 2607.5139 USA | 1967 | 10219 | 12567 | 2607.5139 USA | 1968 | 10600 | 13405 | 2607.5139 (4 rows)
The average production in our dataset is around 2.6 million barrels per day. The goal of this query is to add this value as a column. It is now easy to compare the current row to the overall average.
Keep in mind that the OVER clause is essential. PostgreSQL is not able to process the query without it:
test=# SELECT country, year, production, consumption, avg(production) FROM t_oil;
ERROR: column "t_oil.country" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT country, year, production, consumption, avg(productio...
This actually makes sense because the average has to be defined precisely. The database engine cannot just guess at any value.
- Unreal Engine:Game Development from A to Z
- 輕松學(xué)C語言
- 3D Printing with RepRap Cookbook
- Getting Started with MariaDB
- Getting Started with Containerization
- OpenStack Cloud Computing Cookbook(Second Edition)
- 具比例時(shí)滯遞歸神經(jīng)網(wǎng)絡(luò)的穩(wěn)定性及其仿真與應(yīng)用
- 智能生產(chǎn)線的重構(gòu)方法
- Building a BeagleBone Black Super Cluster
- Mastering Exploratory Analysis with pandas
- 數(shù)字多媒體技術(shù)基礎(chǔ)
- 典型Hadoop云計(jì)算
- 基于人工免疫原理的檢測系統(tǒng)模型及其應(yīng)用
- 設(shè)計(jì)模式
- Data Analysis with R(Second Edition)