如何按大小写和顺序排序?

时间:2020-07-15 00:15:33

标签: sql postgresql sql-order-by

我要查询我的下一张桌子

|id |Name|type      |
---------------------
|1  |B   |Secondary |
|2  |A   |Scholar   |
|3  |C   |University|

这可能是sql查询:

select * from invite order by  
        case "type" 
             when 'Scholar'   then 1 
             when 'Secondary' then 2
             when 'University' then 3
         end asc;

但是现在我需要按情况订购: 示例:when 'Scholar' then 1 desc

有可能吗?

我的目标是按 id 进行排序,并按类型的示例进行排序:

|id |Name|type      |
---------------------
|1  |B   |Secondary |
|2  |B   |Secondary |
|3  |B   |Secondary |
|4  |A   |Scholar   |
|5  |A   |Scholar   |
|6  |C   |University|
|7  |A   |Scholar.  |

结果将是:

|id |Name|type      |
---------------------
|7  |A   |Scholar.  |
|5  |A   |Scholar   |
|4  |A   |Scholar   |
|3  |B   |Secondary |
|2  |B   |Secondary |
|1  |B   |Secondary |
|6  |C   |University|

2 个答案:

答案 0 :(得分:2)

我想你想要

order by  
    case "type" 
         when 'Scholar'    then 1 
         when 'Secondary'  then 2
         when 'University' then 3
    end,
    id desc

您也可以使用数组代替条件逻辑:

order by
    array_position(array['Scholar', 'Secondary', 'University'], "type"),
    id desc

答案 1 :(得分:2)

您的问题表明,每个小组都需要一个新的方向:

order by (case "type" 
             when 'Scholar'   then 1 
             when 'Secondary' then 2
             when 'University' then 3
          end) asc;
         (case when "type" = Scholar then id end) desc,
         id asc;

但是,您的示例表明您只想要第二个order byid desc