Reputation: 5384
The simplified version is this: I have a table with two fields. The first field, trx
, will always have a value. The second field, tstop
, can be either null or a timestamp.
I would like to organize the output from the select such that the first "group" of records all have tstop of null, the remaining records have a non-null value of tstop
. Each group is ordered by trx
desc.
How is this done?
TABLE rx
(
recid serial NOT NULL,
trx timestamp without time zone NOT NULL,
tstop timestamp without time zone
)
Example values:
recid trx tstop
36; "2014-06-10 13:05:16"; "";
113759; "2014-06-10 13:05:16"; "";
33558; "2014-03-31 18:08:15"; "2014-03-31 18:08:15";
12535; "2014-03-31 18:08:15"; "";
660; "2014-03-31 18:05:59"; "";
144209; "2014-03-30 19:21:14"; "";
Desired Output:
recid trx tstop
36; "2014-06-10 13:05:16"; "";
113759; "2014-06-10 13:05:16"; "";
12535; "2014-03-31 18:08:15"; "";
660; "2014-03-31 18:05:59"; "";
144209; "2014-03-30 19:21:14"; "";
33558; "2014-03-31 18:08:15"; "2014-03-31 18:08:15";
This obviously will not work:
select * from rx order by trx desc;
Upvotes: 2
Views: 125
Reputation:
Just order by
the columns and use the option nulls first
to make null
values appear first:
SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC
Upvotes: 1
Reputation: 175556
You could use IS NULL
:
SELECT *
FROM rx
ORDER BY tstop IS NULL DESC, trx DESC
Upvotes: 2
Reputation: 389
ORDER BY (CASE WHEN tstop IS NULL THEN 1 ELSE 0 END) DESC, tstop DESC
Upvotes: 0