在 PostgreSQL 中按空值对 select 输出进行分组
Grouping select output by null value in PostgreSQL
简化版本是这样的:我有一个包含两个字段的 table。第一个字段 trx
将始终有一个值。第二个字段 tstop
可以为 null 或时间戳。
我想组织 select 的输出,使得前 "group" 条记录的 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;
ORDER BY (CASE WHEN tstop IS NULL THEN 1 ELSE 0 END) DESC,
tstop 描述
您可以使用 IS NULL
:
SELECT *
FROM rx
ORDER BY tstop IS NULL DESC, trx DESC
仅 order by
列并使用选项 nulls first
使 null
值首先出现:
SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC
简化版本是这样的:我有一个包含两个字段的 table。第一个字段 trx
将始终有一个值。第二个字段 tstop
可以为 null 或时间戳。
我想组织 select 的输出,使得前 "group" 条记录的 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;
ORDER BY (CASE WHEN tstop IS NULL THEN 1 ELSE 0 END) DESC, tstop 描述
您可以使用 IS NULL
:
SELECT *
FROM rx
ORDER BY tstop IS NULL DESC, trx DESC
仅 order by
列并使用选项 nulls first
使 null
值首先出现:
SELECT *
FROM rx
ORDER BY tstop DESC NULLS FIRST, trx DESC