A
A
Alexander Wolf2015-02-18 13:09:18
PostgreSQL
Alexander Wolf, 2015-02-18 13:09:18

How to sort in SQL?

Hey! I have a table:

idcounttostatususer_idcreated_atupdated_at
one50000one2015-02-18 13:54:44.9120002015-02-18 12:54:47.328000
240002one2015-02-18 14:04:51.7000002015-02-18 14:04:53.487000
Where status takes the values ​​0, 1, 2...n
I need to sort in such a way that first there are rows where satatus == 0, and then all the rest (which should no longer be sorted by status). I also need all rows to be sorted by the upadted_at, desc field.
Ideally, of course, ALL fields should be displayed where status = 0, and, also, if they turned out to be < 50, then we supplement up to 50 with the remaining lines. And if there are more of them, then we do not display fields where the status is not 0.
Any ideas how to implement this? :)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
DenOk, 2015-02-18
@mannaro

Use CASE:
select status,
case
when status = 0 then
0
else
1
end as status_tmp ,
updated_at
from your_table t
order by status_tmp , updated_at
desc I use Oracle, but I know CASE is also in PostgreSQL. And it is better to implement checks for the number of lines and the actions following them in a stored procedure.

V
Vsevolod, 2015-02-18
@sevka_fedoroff

you need to add a new field of type select IF(status>0,1,0) status1 to the select
and then order by status1, updated_at DESC

V
Vladimir Martyanov, 2015-02-18
@vilgeforce

ORDER BY status, upadted_at - won't work?

K
krypt3r, 2015-02-18
@krypt3r

... ORDER BY status, updated_at DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question