按查询的where子句中的字段顺序对sql查询的结果进行排序

时间:2013-05-07 17:50:13

标签: sql sorting sql-order-by

我想根据查询的内容对此查询的结果进行排序:

这里是:

SELECT a from Frais a where a.libelle = 'FRET' or a.libelle = 'Douane' or a.libelle = 'Transitaire'

我希望首先有FRETDouane之后的记录等等

order by libelle 

无法解决根据字母顺序asc或desc

对它们进行排序的问题

3 个答案:

答案 0 :(得分:4)

一种选择是使用CASE声明:

SELECT * 
FROM Frais a 
WHERE a.libelle = 'FRET' 
   OR a.libelle = 'Douane' 
   OR a.libelle = 'Transitaire'
ORDER BY 
   CASE 
     WHEN a.libelle = 'FRET' THEN 1
     WHEN a.libelle = 'Douane' THEN 2
     WHEN a.libelle = 'Transitaire' THEN 3
   END

答案 1 :(得分:3)

SELECT a from Frais a where a.libelle = 'FRET' or a.libelle = 'Douane' or a.libelle = 'Transitaire'
order by case a.libelle when 'FRET' then 0 when 'Douane' then 1 when 'Transitaire' then 2 end

答案 2 :(得分:0)

您也可以通过将值放在具有明确排序的“临时”表中来执行此操作:

select f.*
from frais f join
     (select 'FRET' as val, 1 as ord union all
      select 'Douane', 2 union all
      select 'Transitaire', 3
     ) vals
     on f.libelle = vals.val
order by vals.ord