【问题标题】:How to handle NULL values when sorting?排序时如何处理 NULL 值?
【发布时间】:2019-10-16 21:25:09
【问题描述】:

我正在寻找一种在 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

【问题讨论】:

  • 你能分享一个小数据样本和预期输出吗?
  • 你用 Python 还是 SQL 排序?
  • 我在 sql 中排序,但代码在 Python 中。我想先有排序的数值,最后是 NULL 值,或者先有 NULLS,然后按顺序排序。
  • 这是我为获得结果而进行的 api post call 示例:{ "indicators": ["mP"], "limit": 10, "sort": ["mP: asc"],

标签: python sql sorting null


【解决方案1】:

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

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

还找到了一个nice reference 用于使用空值进行排序。

【讨论】:

    【解决方案2】:

    在过滤数据之间使用 union all 的另一种实现方式

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

    【讨论】:

      【解决方案3】:

      你可以试试这样的:

      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
      

      如果您想在顶部获取 null,请使用 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
      

      在底部获得 null:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-04
        • 1970-01-01
        相关资源
        最近更新 更多