Order By Date desc 评估 01-01-1970 高于其他所有内容

Order By Date desc evaluates 01-01-1970 higher then everything else

我有以下简化查询

SELECT 
   id
   to_char(execution_date, 'YYYY-MM-DD') as execution_date
FROM schema.values
ORDER BY execution_date DESC, id DESC

execution_date 可以为空。

如果 execution_date 中没有值,它将默认设置为 1970-01-01。我的问题是,以下 table 值将导致 1970-01-01 被视为最新日期的结果。

Table:

id execution_date
1
2 2020-01-01
3 2022-01-02
4

我期望的结果

id execution_date
3 2022-01-02
2 2020-01-01
4 1970-01-01
1 1970-01-01

我得到了什么

id execution_date
4 1970-01-01
1 1970-01-01
3 2022-01-02
2 2020-01-01

我怎样才能得到正确的顺序,如果日期为空,是否可以轻松地 return 一个空的 varchar?

如果你 table 有 NULL 值,而不是空值,你可以尝试使用 nulls last :

with t as (select 1 as id, NULL::date as dt
union select
2, '2020-01-01'::date
union select
3, '2020-01-02'::date
union select
4, NULL::date)
select * 
from t
order by t.dt desc nulls last, id desc;

它也适用于空文本值:

with t as (select 1 as id, ''::text as dt
union select
2, '2020-01-01'::text
union select
3, '2020-01-02'::text
union select
4, NULL::text)
select * 
from t
order by t.dt desc nulls last, id desc

如果您需要将 NULL 日期更改为 1970 年,只需使用 COALESCE() :

with t as (select 1 as id, NULL::date as dt
union select
2, '2020-01-01'::date
union select
3, '2020-01-02'::date
union select
4, NULL::date)
select coalesce(t.dt, '1970-01-01'::date) as dt
from t
order by t.dt desc nulls last, id desc

这是dbfiddle

https://dbfiddle.uk/?rdbms=postgres_14&fiddle=5d1fc31a3cf2d3121092f2446cce87e5

SELECT 
   id,
   to_char(coalesce( execution_date, '1970-01-01'::date), 'YYYY-MM-DD') as execution_date
FROM values1
ORDER BY execution_date DESC, id DESC;

只见树木不见森林...

这是简单的解决方案:

SELECT 
   id
   CASE WHEN execution_date IS NULL THEN ''
            ELSE to_char(execution_date, 'YYYY-MM-DD') END 
            AS execution_date
FROM schema.values
ORDER BY execution_date DESC, id DESC