下面是我的表(tracking_data)的示例数据的结构。我想在最后找到所有无法送达的包裹(cte_tracking_status_id = 10013)(有一些)。下面是一个包裹状态变化的例子。
CREATE TABLE tracking_data_event
(
cte_id bigint NOT NULL DEFAULT nextval('tracking_data_event_cte_id_seq'::regclass),
cte_tracking_number text NOT NULL,
cte_tracking_status_id smallint NOT NULL,
cte_timestamp timestamp without time zone,
cte_description text,
CONSTRAINT tracking_data_event_pkey PRIMARY KEY (cte_id)
)
Postgres版本:9.5
cte_id | cte_tracking_number | cte_tracking_status_id | cte_timestamp | cte_description
---------------------------------------------------------------------------
8546809 | CO-141998094 | 1 | 19-04-2017 | LABEL_PRINTED
8708871 | CO-141998094 | 10014 | 19-04-2017 |
9519695 | CO-141998094 | 10014 | 27-04-2017 |
8708872 | CO-141998094 | 10004 | 27-04-2017 | BPOST_LM_PARCEL_PROCESSED
9519745 | CO-141998094 | 10014 | 27-04-2017 |
8708933 | CO-141998094 | 10010 | 27-04-2017 | BPOST_LM_PARCEL_STORED
9519781 | CO-141998094 | 10014 | 27-04-2017 |
8708969 | CO-141998094 | 10004 | 27-04-2017 | BPOST_LM_PARCEL_PROCESSED
8728290 | CO-141998094 | 10004 | 27-04-2017 | BPOST_LM_TRANSIT
8728291 | CO-141998094 | 10004 | 27-04-2017 | BPOST_LM_TRANSIT
9519829 | CO-141998094 | 10014 | 27-04-2017 |
8728292 | CO-141998094 | 10004 | 27-04-2017 | BPOST_LM_PARCEL_PROCESSED
8743559 | CO-141998094 | 10004 | 28-04-2017 | BPOST_LM_TRANSIT
8743560 | CO-141998094 | 10004 | 28-04-2017 | BPOST_LM_TRANSIT
8767949 | CO-141998094 | 10009 | 01-05-2017 | BPOST_LM_MISSED_DELIVERY
9519855 | CO-141998094 | 10013 | 01-05-2017 | BPOST_LM_UNDELIVERABLE
8767950 | CO-141998094 | 10004 | 01-05-2017 | BPOST_LM_TRANSIT
8789169 | CO-141998094 | 20 | 02-05-2017 | BPOST_LM_DELIVERED
答案 0 :(得分:0)
如果“last”表示按时间戳排序的最后一个,那么您可以通过多种方式执行此操作。一种方法使用distinct on
:
select t.*
from (select distinct on (cte_tracking_number) t.*
from t
order by cte_tracking_number, cte_timestamp desc
) t
where cte_tracking_status_id = 10013;