-1

我正在尝试学习 sql,但我有一个问题。如何按天的逻辑顺序对输出进行排序?例如,我希望从 'Monday' 到 'Sunday' 订购 HIREDAY 的人。

select first_name,
TO_CHAR(hire_date,'Day') as "HIREDAY"
from employees
order by HIREDAY;

输出:

Daniel  Friday   
Ismael  Friday    
Gerald  Monday   
Renske  Monday   
Jason   Monday   
Vance   Saturday 
Jenni   Saturday 
Michael Saturday 
John    Sunday   
James   Sunday   
Matthew Sunday   
Payam   Thursday 
Irene   Thursday 
Michael Tuesday  
Kevin   Tuesday  
Anthony Wednesday
Karen   Wednesday
4

2 回答 2

1

您可以使用以下case语句执行此操作:

order by (case when trim(Hire_Day) = 'Monday' then 1
               when trim(Hire_Day) = 'Tuesday' then 2
               when trim(Hire_Day) = 'Wednesday' then 3
               when trim(Hire_Day) = 'Thursday' then 4
               when trim(Hire_Day) = 'Friday' then 5
               when trim(Hire_Day) = 'Saturday' then 6
               when trim(Hire_Day) = 'Sunday' then 7
          end)

在 Oracle 中,您还可以使用DAYOFWEEK()

order by DAYOFWEEK(hire_date)

或按 to_char(Hire_Day, 'D') 订购

于 2013-04-27T16:42:45.217 回答
0

试试这个: select first_name to_char((hire_date),'fmD') "Day" from employees order by "Day";

在此您将获得正确的天数顺序。在您的情况下,从 to_char 开始的日期名称是按字母顺序排列的,这不是必需的。

于 2013-04-27T17:47:03.903 回答