如何根据客户的起始和结束位置排列列表?

x6492ojm  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(262)

我有下表,我想找出哪些客户在他/她的出发地点是另一位在他/她之前<=5分钟出发的客户的出发地点。
例如,我有:

DT                    Customer_Name       Start_location   End_location    Trip_fare
2019-11-01 08:17:42   Jane                  A                 B            $10
2019-11-01 08:18:02   Mary                  C                 A            $7
2019-11-01 08:18:04   Tom                   B                 D            $12
2019-11-01 08:20:11   Harry                 E                 C            $20
2019-11-01 08:21:22   Alex                  D                 A            $5
2019-11-01 08:24:30   Sally                 C                 B            $8

这就是我想要的:

DT                    Customer_Name    Start_location   End_location   
2019-11-01 08:17:42   Jane              A                 B
2019-11-01 08:18:04   Tom               B                 D  (cause Tom's start_location = B = Jane's end_location and the time difference between the 2 trips is within 5 minutes)
2019-11-01 08:21:22   Alex              D                 A
2019-11-01 08:20:11   Harry             E                 C 
2019-11-01 08:24:30   Sally             C                 B

在这里,玛丽已经从列表中删除,因为她的起始位置='c',这不是简的结束位置,简在她之前旅行了<=5分钟。
我为这个看起来很混乱的问题道歉。如果你需要进一步的澄清,一定要告诉我!
非常感谢你的帮助!

anauzrmj

anauzrmj1#

我有下表,我想找出哪些客户在他/她的出发地点是另一位在他/她之前<=5分钟出发的客户的出发地点。
你对问题的描述表明 not exists :

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.end_loc = t.start_loc and
                        t2.dt < t.dt and
                        t2.dt >= t.dt - interval '5' minute
                 );

然而,汤姆、亚历克斯和萨莉都被除名了。从你对这个问题的描述来看,我认为这是正确的。
这是一把小提琴。

1aaf6o9v

1aaf6o9v2#

由于查询与来自同一个表的客户相关,因此需要一个自联接。也就是说,您将表与自身连接起来。

SELECT ... FROM mytable JOIN mytable ...

要区分表的一个“示例”和另一个示例,需要别名:

SELECT ... FROM mytable t1 JOIN mytable t2 ...

你需要加入条件,这就是你的两个客户的关系。在您的示例中,这非常简单:

SELECT tcust.name  AS name, 
       tother.name AS other_name
  FROM mytable tcust 
  JOIN mytable tother
    ON tcust.start_loc = tother.end_loc
   AND tcust.dt       >= tother.dt - INTERVAL '5' MINUTE;

但是,这个查询得到的结果略有不同。你能找出原因吗?

CREATE TABLE mytable (
  dt DATE, name VARCHAR2(30 CHAR), start_loc VARCHAR2(5 CHAR), 
  end_loc VARCHAR2(5 CHAR), fare NUMBER);

INSERT INTO mytable VALUES (TIMESTAMP '2019-11-01 08:17:42', 'Jane',  'A', 'B', 10);
INSERT INTO mytable VALUES (TIMESTAMP '2019-11-01 08:18:02', 'Mary',  'C', 'A', 7);
INSERT INTO mytable VALUES (TIMESTAMP '2019-11-01 08:18:04', 'Tom',   'B', 'D', 12);
INSERT INTO mytable VALUES (TIMESTAMP '2019-11-01 08:20:11', 'Harry', 'E', 'C', 20);
INSERT INTO mytable VALUES (TIMESTAMP '2019-11-01 08:21:22', 'Alex',  'D', 'A',  5);
INSERT INTO mytable VALUES (TIMESTAMP '2019-11-01 08:24:30', 'Sally', 'C', 'B',  8);

结果:

NAME   OTHER_NAME
Tom    Jane 
Jane   Mary 
Alex   Tom  
Mary   Harry
Sally  Harry
Jane   Alex

这个问题解释了5分钟的减法。

相关问题