HybridDB for PG、Greenplum 排序nulls first|last的 SQL写法实现

标签

PostgreSQL , Greenplum


背景

Greenplum并不支持nulls first或last语法,例如:

select * from tbl order by id nulls first;  
  
select id, last_value(key) over (partition by gid order by crt_time nulls first) from tbl ;   

这两句在PostgreSQL可以支持,但是在Greenplum中不支持。

Greenplum实现排序nulls first|last

在PG中支持多列排序,同时支持boolean类型,true 大于 false。

利用这个特性,我们可以在排序时调整字段nulls排在前面还是后面。

select * from tbl order by (id is not null), id;  
  
相当于  
  
select * from tbl order by id nulls first;  
select * from tbl order by (id is null), id;  
  
相当于  
  
select * from tbl order by id nulls last;  

这样就能实现nulls first或last了。

postgres=# select (id is null),* from tbl order by (id is null), id;  
 ?column? | id   
----------+----  
 f        |  1  
 f        |  2  
 f        |  3  
 t        |     
(4 rows)  
  
postgres=# select (id is not null),* from tbl order by (id is not null), id;  
 ?column? | id   
----------+----  
 f        |     
 t        |  1  
 t        |  2  
 t        |  3  
(4 rows)  

窗口函数中使用也一样。

select id, last_value(key) over (partition by gid order by (crt_time is not null), crt_time) from tbl ;   

参考

https://discuss.pivotal.io/hc/en-us/articles/205803497-Sorting-ORDER-BY-of-data-which-has-NULL-values

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值