在PostgreSQL中按空值分组选择输出

在PostgreSQL中按空值分组选择输出,sql,database,postgresql,postgresql-9.5,Sql,Database,Postgresql,Postgresql 9.5,简化版是这样的:我有一个带有两个字段的表。第一个字段,trx,总是有一个值。第二个字段,tstop,可以是null或时间戳 我希望对select的输出进行组织,使第一个“组”记录的tstop值都为null,其余记录的非null值为tstop。每组按trxdesc排序 这是怎么做到的 TABLE rx ( recid serial NOT NULL, trx timestamp without time zone NOT NULL, tstop timestamp without ti

简化版是这样的:我有一个带有两个字段的表。第一个字段,
trx
,总是有一个值。第二个字段,
tstop
,可以是null或时间戳

我希望对select的输出进行组织,使第一个“组”记录的tstop值都为null,其余记录的非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;
ORDER BY(tstop为NULL时为1,否则为0)DESC,
tstop DESC

您可以使用的
为NULL

SELECT *
FROM rx
ORDER BY tstop IS NULL DESC, trx DESC

只需按列排序,然后使用选项
null first
使
null
值首先出现:

SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC

NULLS FIRST
是一个不错的选择,但检查最后两条记录,OP希望按NULL/NOT NULL分组,并按trx DESCWorks排序。谢谢