代码之家  ›  专栏  ›  技术社区  ›  Blair Anderson

PostgreSQL按两个日期中的最早日期排序?

  •  0
  • Blair Anderson  · 技术社区  · 6 年前

    我需要按“A列的最近版本,回退到B列”对Postgres表进行排序。

    如果我的桌子像这样: id , reminder_at , updated_at

    1, 01-11-2019, 12-01-2018
    2, null,       01-04-2019
    3, null,       01-02-2019
    4, 01-01-2019, 01-04-2019
    

    预期的排序输出为

    4, 01-01-2019, 01-04-2019 # 01-01-2019 is soonest 
    3, null,       01-02-2019 # then 01-02-2019
    2, null,       01-04-2019 # then 01-04-2019
    1, 01-11-2019, 12-01-2018 # then 01-11-2019
    

    我目前正在使用应用程序代码进行此操作,我更愿意在SQL中进行此操作

    例如,如果记录1的提醒\变为空,那么它将立即变为顶部,因为 更新的AT 日期是最早的

    目前:

    SELECT * 
    FROM "tasks" 
    WHERE completed_at IS NULL
    ORDER by reminder_at, updated_at
    

    用正确答案编辑:

    SELECT * 
    FROM "tasks" 
    WHERE completed_at IS NULL
    ORDER by COALESCE(reminder_at, updated_at)
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Joe Love    6 年前

    使用聚结。它选择第一个非空值。

     select * from tab
     order by coalesce(col1, col2)
    

    如果相反,您希望使用两个日期中较大的一个。然后使用最大值()。

     select * from tab
     order by greatest(col1, col2)
    
        2
  •  0
  •   ffejrekaburb    6 年前

    我正在将您的数据格式解释为mm-dd。是否应该在输出中翻转3和2,第二个在第四个之后?

    以下内容有效吗?

    选择id,reminder_at,updated_at,greatest(coalesce(reminder_at,'1/1/1900'),coalesce(updated_at,'1/1/1900'))作为测试顺序中greatest(coalesce(reminder_at,'1/1/1900'),coalesce(updated_at,'1/1/1900')的测试列;