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

Abstracting window clauses

A windowing function allows us to add columns to the result set that have been calculated on the fly. However, what happens quite frequently is that many columns are based on the same window. Putting the same clauses into your queries over and over again is definitely not a good idea, because your queries will be hard to read and therefore hard to maintain.

The WINDOW clause allows developers to predefine a window and use it at various places in the query. Here is how it works:

SELECT country, year, production, 
min(production) OVER (w),
max(production) OVER (w)
FROM t_oil
WHERE country = 'Canada'
AND year BETWEEN 1980
AND 1985
WINDOW w AS (ORDER BY year);

country | year | production | min | max --------+-------+------------+------+------
Canada | 1980 | 1764 | 1764 | 1764
Canada | 1981 | 1610 | 1610 | 1764
Canada | 1982 | 1590 | 1590 | 1764
Canada | 1983 | 1661 | 1590 | 1764
Canada | 1984 | 1775 | 1590 | 1775
Canada | 1985 | 1812 | 1590 | 1812
(6 rows)

The example shows that min and max will use the same clause.

Of course, it is possible to have more than just one WINDOW clause—PostgreSQL does not impose serious restrictions on users here.

主站蜘蛛池模板: 康马县| 瑞昌市| 永昌县| 绍兴县| 仁化县| 峨眉山市| 临漳县| 台中市| 吐鲁番市| 鹿泉市| 延庆县| 保亭| 曲麻莱县| 凤翔县| 中卫市| 湘乡市| 岢岚县| 庆城县| 井冈山市| 东辽县| 安西县| 嵊泗县| 高陵县| 南通市| 镇雄县| 抚远县| 城口县| 嘉荫县| 洱源县| 肥西县| 白玉县| 乐陵市| 麻栗坡县| 天峻县| 黎城县| 焦作市| 思茅市| 尉犁县| 靖宇县| 建德市| 塔河县|