官术网_书友最值得收藏!

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 second aggregate will take care of more recent data.

Note that if it is possible to move conditions to a WHERE clause it is always more desirable as less data has to be fetched from the table. FILTER is only useful if the data left by the WHERE clause is not needed by each aggregate.

FILTER works for all kinds of aggregates and offers a simple way to pivot your data.

主站蜘蛛池模板: 天镇县| 光泽县| 闸北区| 即墨市| 固始县| 正镶白旗| 宣城市| 法库县| 昭苏县| 昌江| 金川县| 兴文县| 宝丰县| 永仁县| 上林县| 嘉祥县| 伊宁县| 册亨县| 铅山县| 定西市| 宜兴市| 文安县| 桐城市| 志丹县| 黄浦区| 赞皇县| 普格县| 阿图什市| 鄂尔多斯市| 定州市| 舒城县| 于都县| 苍南县| 富裕县| 额济纳旗| 平乐县| 莱芜市| 广州市| 泾阳县| 龙门县| 北安市|