如何使用PSQL将该表逐行拆分为两个?

时间:2017-04-05 13:02:24

标签: sql postgresql psql

我有一张表(表A),按时间记录出租车订单的每个来源和目的地,现在我想找到第一个原点(即第2行),然后逐行将O和D配对,直到最后一个目的地(即第9行),结果应该像表B.我如何实现它?

image here

表A

Time    GPS_Point                   Status
633     POINT(121.314917 31.149205) Destination
62323   POINT(121.535798 31.25828)  Origin
62328   POINT(121.535798 31.25828)  Destination
62332   POINT(121.535798 31.25828)  Origin
62429   POINT(121.5358 31.258278)   Destination
62637   POINT(121.535788 31.25827)  Origin
62647   POINT(121.535788 31.25827)  Destination
62731   POINT(121.535795 31.25826)  Origin
62741   POINT(121.535795 31.25826)  Destination
62812   POINT(121.535793 31.25826)  Origin

表B

Origin_Time Origin_GPS_Point    Destination_Time    Destination_GPS_Point
62323   POINT(121.535798 31.25828)  62328   POINT(121.535798 31.25828)
62332   POINT(121.535798 31.25828)  62429   POINT(121.5358 31.258278)
62637   POINT(121.535788 31.25827)  62647   POINT(121.535788 31.25827)
62731   POINT(121.535795 31.25826)  62741   POINT(121.535795 31.25826)

2 个答案:

答案 0 :(得分:1)

你可以试试这个(但假设一些概念,作为Orig / Dest的顺序而没有任何中断)(我为GPS_POINT使用了一些假值,并且' O'作为原点和' D&# 39;作为目的地)。

    CREATE TABLE TABLEA (TIME INT, GPS_POINT VARCHAR(10), STATUS VARCHAR(1));
    INSERT INTO TABLEA VALUES (633,'p1','D');
    INSERT INTO TABLEA VALUES (62323,'p2','O');
    INSERT INTO TABLEA VALUES (62328,'p3','D');
    INSERT INTO TABLEA VALUES (62332,'p4','O');
    INSERT INTO TABLEA VALUES (62429,'p5','D'); 
    INSERT INTO TABLEA VALUES (62637,'p6','O');
    INSERT INTO TABLEA VALUES (62647,'p7','D'); 
    INSERT INTO TABLEA VALUES (62650,'p8','O');

    SELECT ORIGIN_TIME, ORIGIN_GPS, DEST_TIME, DEST_GPS FROM 
     (SELECT TIME AS ORIGIN_TIME, GPS_POINT AS ORIGIN_GPS, ROW_NUMBER() OVER (ORDER BY TIME) AS RN_O
    FROM TABLEA
    WHERE STATUS='O') A
     LEFT JOIN (SELECT TIME AS DEST_TIME, GPS_POINT AS DEST_GPS, ROW_NUMBER() OVER (ORDER BY TIME) AS RN_D
                FROM TABLEA
                WHERE STATUS='D'
                AND TIME> (SELECT MIN(TIME) FROM TABLEA)
                ) B ON A.RN_O = B.RN_D
WHERE DEST_TIME IS NOT NULL /* IF YOU WANT OMITS LAST "O" ROW WITHOUT "D" */
    ;

输出:

    origin_time origin_gps  dest_time   dest_gps
1   62323   p2  62328   p3
2   62332   p4  62429   p5
3   62637   p6  62647   p7

答案 1 :(得分:0)

使用此查询:

select a.Time as 'Origin_Time', a.GPS_Point as 'Origin_GPS_Point', aa.Time as 'Destination_Time', aa.GPS_Point as 'Destination_GPS_Point'
from TABLE_A a
JOIN TABLE_A aa on a.GPS_Point=aa.GPS_Point and aa.Status='Destination' and a.Status='Origin'
相关问题