我正在使用rails和postgresql来填充dataTable,我想知道是否有一种方法可以改变NULLS的默认行为,即较高的值(排序时在大数字之后(,使其在排序中等于低于0。据我所知,这是一种内置的postgresql行为,所以我认为我必须使用sql调用来实现这一点。我需要将其应用于所有列,以便它与DataTables排序ASC/DESC功能一起工作。
示例一些类似于的功能
def get_raw_records
Analytics::Database.where(id: 7).order('give nulls < 0 value here for all columns?')
end
NULLS FIRST/LAST没有提供此功能,我需要类似于coalize的东西,它理想情况下不返回排序实例,但在客户端排序时,会更改大值之后放置的null的默认行为
您可以使用
order by coalesce(col_name,-1)
接近Sabari建议:
db=# with c(v) as (values('1'),('a'),(null),(null),('b'))
select * from c
order by coalesce(v,'-infinity') asc;
v
---
1
a
b
(5 rows)
db=# with c(v) as (values('1'),('a'),(null),(null),('b'))
select * from c
order by coalesce(v,'-infinity') desc;
v
---
b
a
1
(5 rows)
这里使用CCD_ 1,而不是零以下的固定整数。它与text
一起工作很好(不是因为text
理解infinity
,而是因为-
在[a-z]
或[0-9]
之前(,但与正常的integer
不工作。当然,您可以将其转换为float
:
db=# with c(v) as (values(1::float),(3),(null),(null),(-9))
select * from c
order by coalesce(v,'-infinity') desc;
v
----
3
1
-9
(5 rows)
db=# with c(v) as (values(1::float),(3),(null),(null),(-9))
select * from c
order by coalesce(v,'-infinity') asc;
v
----
-9
1
3
(5 rows)
with本身就很危险(好吧,不是分类((而且很丑陋(。这就引出了答案——我从脑海中看不到好的解决方案。。。您应该更好地为不同的数据类型设置单独的边界。
在Postgres中,您可以在order by子句中指定NULL排序方式:
select 1 as col UNION select 2 UNION SELECT NULL ORDER BY col ASC NULLS FIRST;
您可以指定NULLS FIRST或NULLS LAST
请参阅https://www.postgresql.org/docs/current/static/queries-order.html