- Mastering PostgreSQL 10
- Hans Jürgen Sch?nig
- 228字
- 2021-06-30 19:04:01
Combining grouping sets with the FILTER clause
In real-world applications, grouping sets can often be combined with FILTER clauses. The idea behind the FILTER clause is to be able to run partial aggregates.
Here is an example:
test=# SELECT region,
avg(production) AS all, avg(production) FILTER (WHERE year < 1990) AS old, avg(production) FILTER (WHERE year >= 1990) AS new FROM t_oil GROUP BY ROLLUP (region);
region | all | old | new
---------------+----------------+----------------+----------------
Middle East | 1992.603686635 | 1747.325892857 | 2254.233333333
North America | 4541.362318840 | 4471.653333333 | 4624.349206349
| 2607.513986013 | 2430.685618729 | 2801.183150183 (3 rows)
The idea here is that not all columns will use the same data for aggregation. The FILTER clauses allow you to selectively pass data to those aggregates. In my example, the second aggregate will only consider data before 1990, while the third aggregate will take care of more recent data.
FILTER works for all kinds of aggregates and offers a simple way to pivot your data. Also, FILTER is faster than mimicking the same behavior with CASE WHEN ... THEN NULL ... ELSE END. You can find some real performance comparison here: https://www.cybertec-postgresql.com/en/postgresql-9-4-aggregation-filters-they-do-pay-off/.
- PowerShell 3.0 Advanced Administration Handbook
- IoT Penetration Testing Cookbook
- 電腦上網直通車
- Embedded Programming with Modern C++ Cookbook
- 構建高性能Web站點
- Enterprise PowerShell Scripting Bootcamp
- 網絡管理工具實用詳解
- Practical AWS Networking
- 項目實踐精解:C#核心技術應用開發
- Eclipse全程指南
- 深度學習之模型優化:核心算法與案例實踐
- 智能座艙之車載機器人交互設計與開發
- 博弈論與無線傳感器網絡安全
- 機器學習公式詳解
- PostgreSQL Administration Cookbook(9.5-9.6 Edition)