PostgreSQL 高级SQL(二) filter子句

尚学堂给同学们带来全新的Java300集课程啦!java零基础小白自学Java必备优质教程_手把手图解学习Java,让学习成为一种享受_哔哩哔哩_bilibili

本章所用到案例数据来自于上一章节,如果有想使用该数据的读者可以查看上一章节。

    这一章节我们想要了解的是PG聚合操作中使用到的filter子句,这个filter子句是ANSI SQL标准中的关键字,并不是PG的专用SQL关键字。如果我们想了解中国、美国、日本、法国、德国、加拿大从1960~2018年中每隔十年的GDP平均值情况,我们可能会写出着这样的SQL,

select country_name,sum(case when year>=1960 and year<1970 then gdp else null end) as "1960~1969", sum(case when year>=1970 and year<1980 then gdp else null end) as "1970~1979", sum(case when year>=1980 and year<1990 then gdp else null end) as "1980~1989", sum(case when year>=1990 and year<2000 then gdp else null end) as "1990~1999", sum(case when year>=2000 then gdp else null end) as "2000~至今" from country_gdp_year_final where country_code in('CHN','JPN','USA','DEU','CAN','FRA') group by country_name;

case when子句 实现六国每个十年的GDP总值

从上图可以看出美国的经济体量和我们中国的经济体量不是在一个数量级的,中国每隔十年的GDP实现一倍的增速,美国一直飞速发展时期,中国要实现美国的GDP的话粗略估计需要至少30年的时间甚至更久;

回归正题,我们今天的主角是filter子句,ANSI SQL加入filter关键词的主要目的就是替代case when子句,简化case when参与的聚合语句,增加可可读性,我们用同样的filter 子句实现上面的case when参与的聚合操作。

select country_name,sum(gdp) filter(where  year>=1960 and year<1970) as "1960~1969",sum(gdp)  filter(where  year>=1970 and year<1980) as "1970~1979",sum(gdp)  filter(where year>=1980 and year<1990)  as "1980~1989",sum(gdp)  filter(where  year>=1990 and year<2000) as "1990~1999", sum(gdp)  filter(where  year>=2000 ) as "2000~至今" from country_gdp_year_final  where  country_code in('CHN','JPN','USA','DEU','CAN','FRA') group by country_name;


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值