sort result of sql query by order of field in where clause of query

拥有回忆 提交于 2019-12-23 21:18:24

问题


I want to sort the result of this query according to the contains of the query :

here it is :

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

I would like to have the records that have FRET first and Douane after and so on

order by libelle 

doesn't resolve the problem it sort them according to alphabetic order asc or desc


回答1:


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:


One option is to use a CASE statement:

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



回答3:


You can also do this by putting the values in a "temporary" table that has an explicit ordering:

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


来源:https://stackoverflow.com/questions/16425430/sort-result-of-sql-query-by-order-of-field-in-where-clause-of-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!