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

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
云原生数据库 PolarDB 分布式版,标准版 2核8GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

标签

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

相关文章
|
3月前
|
SQL 数据库管理
第二章:基础查询与排序---SQL学习笔记
第二章:基础查询与排序---SQL学习笔记
56 0
|
4月前
|
SQL 存储
SQL组内排序
为什么要用ORDER BY来做,因为是这样的,由于采用的多线程,各个线程触发时间十分相近,但是我们需要对每一个项目进行分组,所以在此处,我们做了一个唯一标识IDENTIFICATION,每个项目每次执行时记录的6条日志里都会存储这个唯一标识。
|
25天前
|
SQL
SQL语句两个字段或多个字段同时order by 排序
SQL语句两个字段或多个字段同时order by 排序
27 0
|
2月前
|
SQL 人工智能 运维
数据库基础入门 — SQL排序与分页
数据库基础入门 — SQL排序与分页
25 0
|
3月前
|
SQL 数据库管理
SQL基础题----基本的SELECT语句、order by排序
SQL基础题----基本的SELECT语句 ambiguous 模糊
173 1
|
3月前
|
SQL 存储 数据库
MS-SQL创建查询排序语句总结
MS-SQL中的查询排序语句(ORDER BY)用于在执行SQL查询后,按照指定列的值对查询结果进行升序或降序排列。
66 0
|
4月前
|
SQL 大数据 HIVE
每天一道大厂SQL题【Day04】大数据排序统计
每天一道大厂SQL题【Day04】大数据排序统计
30 0
|
4月前
|
SQL 关系型数据库 MySQL
【SQL编程】Greenplum 与 MySQL 数据库获取周几函数及函数结果保持一致的方法
【SQL编程】Greenplum 与 MySQL 数据库获取周几函数及函数结果保持一致的方法
37 0
|
4月前
|
SQL
Greenplum【SQL 03】实现树结构+自定义函数+避免函数重复调用+ function cannot execute on a QE slice 问题处理(优化过程全记录)
Greenplum【SQL 03】实现树结构+自定义函数+避免函数重复调用+ function cannot execute on a QE slice 问题处理(优化过程全记录)
34 0
|
4月前
|
SQL 关系型数据库 MySQL
Greenplum【SQL 02】ROW_NUMBER编号函数使用方法举例
Greenplum【SQL 02】ROW_NUMBER编号函数使用方法举例
58 0