SQL语句顺序

时间:2013-04-27 16:39:51

标签: sql sql-order-by

我正在尝试学习sql,我有一个问题。如何按天的逻辑顺序订购输出?例如,我希望从“星期一”到“星期天”的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

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

试试这个: select first_name to_char((hire_date),'fmD')“Day” 来自员工 按“日”排序;

在此,您将获得正确的天数顺序。在您的情况下,来自to_char的天数按字母顺序排序,这不是必需的。