Postgresql: Ordering columns to match custom criteria

风流意气都作罢 提交于 2019-12-06 11:55:41

Try being explicit about the order by:

order by (case when id_clasificacion_doc = 5 then 1
               when id_clasificacion_doc = 3 then 2
               when id_clasificacion_doc = 2 then 3
               when id_clasificacion_doc = 4 then 4
          end)

As @ruakh intimated:

AnimalsPriority (animal varchar, priority numeric)
cat, 2.0
dog, 1.0
moose, 1.1

Animals (animal varchar)
cat
dog
moose


select * from Animals A
inner join AnimalsPriority AP
on A.animal = AP.animal
order by AP.priority

If you "hard-code" the sort-order into the query you must change the query if the priority changes. Keeping the sort-priority as a kind of metadata is more flexible, and if you use a number with a decimal point you can always inject new values into the sort order without having to renumber everything.

I believe your latter example should work as so:

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