- 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.
- 精通Excel VBA
- 大數(shù)據(jù)技術(shù)入門(第2版)
- RPA(機(jī)器人流程自動(dòng)化)快速入門:基于Blue Prism
- 網(wǎng)中之我:何明升網(wǎng)絡(luò)社會(huì)論稿
- 邊緣智能:關(guān)鍵技術(shù)與落地實(shí)踐
- 中文版AutoCAD 2013高手速成
- 青少年VEX IQ機(jī)器人實(shí)訓(xùn)課程(初級(jí))
- 和機(jī)器人一起進(jìn)化
- 大數(shù)據(jù)導(dǎo)論
- 智能小車機(jī)器人制作大全(第2版)
- 單片機(jī)C語言編程實(shí)踐
- 局域網(wǎng)組建與使用完全自學(xué)手冊
- Modern Big Data Processing with Hadoop
- Learn Power BI
- Python Data Mining Quick Start Guide