postgresql如何分组然后得到first_time和last_time,

postgresql how to group by and then get the first_time and the last_time,

event     event_time           arrival_time
7333 | 2018-09-09       | 2018-10-09
7444 | 2018-09-10       | 2018-11-09
7333 | 2018-09-11       | 2018-09-09
7555 | 2018-09-12       | 2018-08-09
7555 | 2018-09-13       | 2018-06-09
7333 | 2018-09-15       | 2018-09-09

然后我要得到结果,在我看来,我们要得到组,然后每个组显示第一个事件时间和最后一个事件时间

event event_first       arrival_first      event_last     arrival_last
7333 | 2018-09-09       | 2018-08-09       | 2018-09-15  |2018-10-09
7444 | 2018-09-10       | 2018-11-09       | 2018-09-10  |2018-11-09
7555 | 2018-09-12       | 2018-06-09       | 2018-09-13  |2018-08-09

曾尝试过这个命令:

SELECT DISTINCT ON (event)
        event, event_time as event_first, event_time as event_last, arrival_time as arrival_first, arrival_time as arrvial_last
FROM   A
ORDER  BY event, event_first, event_last DESC, arrival_first, arrvial_last DESC

但是不行。

您可以尝试使用min获取第一天和max获取最后一天的功能。

CREATE TABLE A(
   event int,
   event_time timestamp,
   arrival_time timestamp
);


insert into a values (7333,'2018-09-09','2018-10-09');
insert into a values (7444,'2018-09-10','2018-11-09');
insert into a values (7333,'2018-09-11','2018-09-09');
insert into a values (7555,'2018-09-12','2018-08-09');
insert into a values (7555,'2018-09-13','2018-06-09');
insert into a values (7333,'2018-09-15','2018-09-09');

查询 1:

SELECT event,
    min(event_time) event_first,
    min(arrival_time) arrival_first,
    max(event_time) event_last,  
    max(arrival_time) arrival_last      
FROM A
group by event   

Results:

| event |          event_first |        arrival_first |           event_last |         arrival_last |
|-------|----------------------|----------------------|----------------------|----------------------|
|  7444 | 2018-09-10T00:00:00Z | 2018-11-09T00:00:00Z | 2018-09-10T00:00:00Z | 2018-11-09T00:00:00Z |
|  7333 | 2018-09-09T00:00:00Z | 2018-09-09T00:00:00Z | 2018-09-15T00:00:00Z | 2018-10-09T00:00:00Z |
|  7555 | 2018-09-12T00:00:00Z | 2018-06-09T00:00:00Z | 2018-09-13T00:00:00Z | 2018-08-09T00:00:00Z |