问题
I'm having trouble sorting the result of a query.
After executing this query:
SELECT id_doc_header, id_clasificacion_doc
FROM cabecera_documento INNER JOIN tipo_doc USING (id_tipo_doc)
INNER JOIN clasificacion_documento USING (id_clasificacion_doc)
WHERE finalizado = 'f' AND cod_exp = '10-APC-2013' AND id_clasificacion_doc in(2,3,4,5)
ORDER BY case when Id_clasificacion_doc = 5 THEN 5 when Id_clasificacion_doc = 3 THEN 3
when Id_clasificacion_doc = 2 THEN 2 when Id_clasificacion_doc = 4 THEN 4 END;
or this:
SELECT id_doc_header, id_clasificacion_doc
FROM cabecera_documento INNER JOIN tipo_doc USING (id_tipo_doc)
INNER JOIN clasificacion_documento USING (id_clasificacion_doc)
WHERE finalizado = 'f' AND cod_exp = '10-APC-2013'
AND id_clasificacion_doc in(2,3,4,5)
ORDER BY id_clasificacion_doc = 5, id_clasificacion_doc = 3, id_clasificacion_doc = 2, id_clasificacion_doc = 4;
the result I get is:
id_doc_header | id_clasificacion_doc
---------------+----------------------
1657 | 2
1658 | 3
1658 | 2
1661 | 4
1663 | 4
1665 | 5
My question is: What can I do to get the results in the next order?
id_doc_header | id_clasificacion_doc
---------------+----------------------
1665 | 5
1658 | 3
1657 | 2
1661 | 4
1663 | 4
I'm using posgresql 9.1.
Thanks in advance.
回答1:
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)
回答2:
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.
回答3:
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;
来源:https://stackoverflow.com/questions/14713798/postgresql-ordering-columns-to-match-custom-criteria