- Mastering PostgreSQL 12
- Hans Jürgen Sch?nig
- 286字
- 2021-08-20 10:00:34
Utilizing windowing functions and analytics
Now that 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 unable to process the query without it:
test=# SELECT country, year, production, consumption, avg(production) FROM t_oil;
psql: 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 any value.
- Machine Learning for Cybersecurity Cookbook
- 樂(lè)高機(jī)器人EV3設(shè)計(jì)指南:創(chuàng)造者的搭建邏輯
- 機(jī)艙監(jiān)測(cè)與主機(jī)遙控
- 電腦上網(wǎng)直通車(chē)
- 大數(shù)據(jù)安全與隱私保護(hù)
- B2B2C網(wǎng)上商城開(kāi)發(fā)指南
- Moodle Course Design Best Practices
- 可編程序控制器應(yīng)用實(shí)訓(xùn)(三菱機(jī)型)
- Troubleshooting OpenVPN
- 內(nèi)模控制及其應(yīng)用
- 大數(shù)據(jù)技術(shù)基礎(chǔ):基于Hadoop與Spark
- Hands-On Data Warehousing with Azure Data Factory
- Linux系統(tǒng)下C程序開(kāi)發(fā)詳解
- 機(jī)器人制作入門(mén)(第4版)
- 穿越計(jì)算機(jī)的迷霧