简化版本是这样的:我有一个包含两个字段的表。第一个字段trx
将始终具有值。第二个字段tstop
可以是null或时间戳。
我想组织select的输出,以便第一个"组"记录都有tstop为null,其余记录的非空值为tstop
。每个组按trx
desc。
这是怎么做到的?
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"; "";
期望的输出:
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";
这显然不起作用:
select * from rx order by trx desc;
答案 0 :(得分:2)
答案 1 :(得分:1)
只需order by
列,然后使用nulls first
选项首先显示null
值:
SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC
答案 2 :(得分:0)
ORDER BY(当tstop为NULL时为1,结束为0)DESC, tstop DESC