排序时如何处理NULL值?

时间:2019-05-31 08:37:17

标签: python sql sorting null

我正在寻找一种在SQL中对DESC或ASC进行排序时最终返回NULL值的方法(信封代码在Python中),也许能够首先根据某些配置重新调整NULL值

我尝试用数字值替换NULL值,但从长远来看,我发现它不是一个合适的解决方案,因为在某些情况下,我需要回溯NULL的来源,为什么我有它并放置数字值可以影响他人的工作并给出错误的结果。

if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql

3 个答案:

答案 0 :(得分:1)

如果仅按语法顺序进行替换,您仍然可以使用空值的数字替换并保留原始值。生成的SQL如下所示:

SELECT col1, col2, col3
FROM Table
ORDER BY COALESCE(col1, -99)

还发现了一个nice reference用于空值排序。

答案 1 :(得分:0)

您可以尝试以下操作:

create table test(col1 varchar(10),col2 float)

insert into test
values('A',1),
('C',2),
('D',null),
('F',4)

而不是像这样排序:

select * from test order by col2 desc
select * from test order by col2 asc

如果要在顶部获得空值,请使用如下所示的case语句进行排序:

select * from test order by case when col2 is null then 0 else 1 end, col2 desc
select * from test order by case when col2 is null then 0 else 1 end, col2 asc

在底部获取空值:

select * from test order by case when col2 is null then 0 else 1 end desc, col2 desc
select * from test order by case when col2 is null then 0 else 1 end desc, col2 asc

答案 2 :(得分:0)

在实现中的替代方法是在过滤后的数据之间使用union all

.... from table_name where column is not null order by column <desc/asc>
UNION ALL
.... from table_name where column is null
相关问题