- Mastering PostgreSQL 9.6
- Hans Jurgen Schonig
- 292字
- 2021-07-09 19:57:25
Utilizing windowing functions and analytics
After discussing 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 take any value, which might be right by doing guesswork.
- 傳感器技術實驗教程
- Learning Apache Spark 2
- 反饋系統:多學科視角(原書第2版)
- 輕松學Java
- 精通Excel VBA
- 21天學通ASP.NET
- 21天學通C#
- 大數據平臺異常檢測分析系統的若干關鍵技術研究
- 水晶石精粹:3ds max & ZBrush三維數字靜幀藝術
- Implementing AWS:Design,Build,and Manage your Infrastructure
- Godot Engine Game Development Projects
- 精通LabVIEW程序設計
- 網絡服務器搭建與管理
- MPC5554/5553微處理器揭秘
- Mastering OpenStack(Second Edition)