2016-12-01 131 views
0

我有不同的STime和ETime的Id1和Id2。對於每組Id1和Id2,我傾向於獲取第一個和最後一個記錄(如輸出中所示)。 我試圖通過ASC和DESC順序使用分區與ID1和ID2,並責令該表:獲取表格中的第一個和最後一個記錄

ROW_NUMBER() OVER(PARTITION BY B.HardwareId, A.TripId ORDER BY StartTime) AS first_record, 
ROW_NUMBER() OVER(PARTITION BY B.HardwareId, A.TripId ORDER BY StopTime DESC) AS last_record 

如預期,我沒有得到結果。

SELECT 
    A.Id1 AS Id1, 
    A.Id2 AS TriId2pId, 
    STime, 
    ETime, 
    Latitude, 
    Longitude 

FROM 
    Tr.T1 AS A 
JOIN 
    Tp.G2 AS B 
ON 
    A.STime < B.DateTime 
    AND A.ETime >= B.DateTime 
    AND A.Id1 = B.Id1 
WHERE 
    (A._PARTITIONTIME BETWEEN TIMESTAMP('2016-11-23') 
    AND TIMESTAMP('2016-11-23') 
    AND A.Id1 IN (976)) 
ORDER BY 
    B.Id1, 
    A.Id2, 
    B.DateTime 



    Id1 Id2 STime    ETime    Latitude Longitude 
    976 715 2016-11-23 13:06:26 2016-11-23 13:23:30 26.2230015 -80.12314  
    976 715 2016-11-23 13:06:26 2016-11-23 13:23:30 26.2229767 -80.12326  
    976 715 2016-11-23 13:06:26 2016-11-23 13:23:30 26.2226944 -80.12344 
    976 800 2016-11-23 13:06:26 2016-11-23 13:24:59 26.2251511 -80.11865  
    976 800 2016-11-23 13:06:26 2016-11-23 13:24:59 26.2251511 -80.11912  
    976 800 2016-11-23 13:06:26 2016-11-23 13:24:59 26.2250233 -80.11929  
    976 800 2016-11-23 13:06:26 2016-11-23 13:24:59 26.2245369 -80.11929   


    Id1 Id2 STime    ETime    Latitude Longitude 
    976 715 2016-11-23 13:06:26 2016-11-23 13:23:30 26.2230015 -80.12314 
    976 715 2016-11-23 13:06:26 2016-11-23 13:23:30 26.2226944 -80.12344 
    976 800 2016-11-23 13:06:26 2016-11-23 13:24:59 26.2251511 -80.11865 
    976 800 2016-11-23 13:06:26 2016-11-23 13:24:59 26.2245369 -80.11929 
+0

首先和最後一個每個Id或整個輸出? –

+0

我正在嘗試每個Id – user3447653

+0

以及「first」和「last」是什麼?它是基於哪個字段? –

回答

1

查詢在你原來的問題不完全匹配,你後面的評論,但仍低於應該幫助你,使你的目標

嘗試

SELECT 
    A.Id AS Id, 
    StartTime, 
    StopTime, 
    Latitude, 
    Longitude 
FROM (
    SELECT 
    A.Id AS Id, 
    StartTime, 
    StopTime, 
    Latitude, 
    Longitude, 
    ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime) AS first_record, 
    ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime DESC) AS last_record 
    FROM 
    Tb1.Ids AS A 
    JOIN 
    Tb2.Points AS B 
    ON 
    A.StartTime <= B.DateTime 
    AND A.StopTime >= B.DateTime 
    AND A.HardwareId = B.HardwareId 
    WHERE 
    (A._PARTITIONTIME BETWEEN TIMESTAMP('2016-11-23') 
    AND TIMESTAMP('2016-11-23')) 
    AND A.Id IN (334) 
) 
WHERE first_record = 1 OR last_record = 1 

理念這裏在內部添加兩個字段將編號從開始和結束的所有行的查詢

ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime) AS first_record, 
    ROW_NUMBER() OVER(PARTITION BY id ORDER BY StartTime DESC) AS last_record 

和tha n離開第一行和最後一行

WHERE first_record = 1 OR last_record = 1 
+0

對不起,當我根據Id1和Id2對其進行分區時,我沒有得到期望的結果。 – user3447653

+0

但你原來的問題只是與Id1,而不是兩個ID!你不是兩個新問題嗎?我正要回答它? –

+0

你能澄清一下,如果你只有一個ID就可以得到你原來的問題的輸出結果嗎? –

相關問題