簡體   English   中英

為什么我的 order by 沒有在日期列中使用 to_char 函數正確排序?

[英]Why my order by is not sorting correctly using to_char function in a date column?

我正在嘗試獲取我的數據庫架構的最后統計信息。 我正在使用這個查詢:

COL last_analyzed FOR A30;
col stale_stats for a11;
col table_name for a40;
col owner for a30;
SET LINESIZE 2000;
select owner,NVL(TO_CHAR(last_analyzed, 'DD/MM/YYYY'), 'NO STATS') last_analyzed,count(*) last_analyzed_count
from dba_tab_statistics
where owner = 'EXAMPLE'
group by owner,TO_CHAR(last_analyzed, 'DD/MM/YYYY')
order by 2 asc
/

但我的排序是:

OWNER                          LAST_ANALYZED                  LAST_ANALYZED_COUNT
------------------------------ ------------------------------ -------------------
EXAMPLE                         07/05/2021                                    1
EXAMPLE                         11/06/2021                                    32
EXAMPLE                         26/04/2021                                    169
EXAMPLE                         27/04/2021                                    1
EXAMPLE                         NO STATS                                      1

在這里,我們可以看到 06 月是在 05 月之后。

日期按字符串排序,因此排序是 100% 正確的。

我的建議是您使用 ISO 標准格式:

select owner,
       coalesce(TO_CHAR(last_analyzed, 'YYYY-MM-DD'), 'NO STATS') last_analyzed,count(*) last_analyzed_count
from dba_tab_statistics
where owner = 'EXAMPLE'
group by owner, TO_CHAR(last_analyzed, 'YYYY-MM-DD')
order by 2 asc;

但是如果你真的想堅持使用定制的日期格式,你可以改用ORDER BY

order by owner, min(dba_tab_statistics.last_analyzed)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM