簡體   English   中英

如何使用PSQL將表格逐行拆分為兩個?

[英]How do I split this table row by row into two using PSQL?

我有一個表(表A),該表按時間記錄出租車訂單的每個出發地和目的地,現在我想找到第一個出發地(即第2行),然后將O和D逐行配對,直到最后一個目的地(即行) 9),結果應類似於表B。如何實現?

圖片在這里

表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)

您可以嘗試這樣做(但要假設Orig / Dest的順序是連續的,沒有任何中斷)(我對GPS_POINT使用了一些偽造的值,“ O”作為起點,“ D”作為終點)。

    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

使用此查詢:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM