Oracle SQL - 来自子查询范围的结果

时间:2013-08-16 05:04:28

标签: sql subquery

我可能会在周末解决这个问题,很难在周五晚些时候关注......

下面的查询1返回一个旅程,在给定位置有到达和离开值。

下面的查询2返回一个旅程,在第二个位置有一个到达和离开值。

这两个查询很简单。

当查询2的离开时间恰好在查询1的到达和离开时间的任何之间时,我想在查询2中返回结果。

从本质上讲,这将为我提供任何在“BER3”已经离开的行程之前离开“BER2”的行程。

查询1

SELECT     RTDEV.TRIP_HEADERS.TRIP_NAME, RTDEV.TRIP_BODIES.ARRIVAL_TIME, RTDEV.TRIP_BODIES.DEPARTURE_TIME
FROM         RTDEV.TRIP_HEADERS INNER JOIN
                      RTDEV.TRIP_BODIES ON RTDEV.TRIP_HEADERS.TME_ID = RTDEV.TRIP_BODIES.TME_ID AND 
                      RTDEV.TRIP_HEADERS.THR_ID = RTDEV.TRIP_BODIES.THR_ID INNER JOIN
                      RTDEV.TNODED ON RTDEV.TNODED.NID = RTDEV.TRIP_BODIES.CURRENT_NODE
WHERE     (RTDEV.TNODED.STRSHORTNAME = 'BER3') AND (RTDEV.TRIP_BODIES.TME_ID = 9860)

查询2

SELECT     TRIP_HEADERS_1.TRIP_NAME, TRIP_BODIES_1.ARRIVAL_TIME, TRIP_BODIES_1.DEPARTURE_TIME
FROM         RTDEV.TRIP_HEADERS TRIP_HEADERS_1 INNER JOIN
                      RTDEV.TRIP_BODIES TRIP_BODIES_1 ON TRIP_HEADERS_1.TME_ID = TRIP_BODIES_1.TME_ID AND 
                      TRIP_HEADERS_1.THR_ID = TRIP_BODIES_1.THR_ID INNER JOIN
                      RTDEV.TNODED TNODED_1 ON TNODED_1.NID = TRIP_BODIES_1.CURRENT_NODE
WHERE     (TNODED_1.STRSHORTNAME = 'BER2') AND (TRIP_BODIES_1.TME_ID = 9860)

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这很简单 - 您可以将query2放在内联视图(FROM子句中的视图)中,如下所示:

SELECT     TRIP_HEADERS_1.TRIP_NAME, TRIP_BODIES_1.ARRIVAL_TIME, TRIP_BODIES_1.DEPARTURE_TIME
FROM         RTDEV.TRIP_HEADERS TRIP_HEADERS_1 INNER JOIN
                      RTDEV.TRIP_BODIES TRIP_BODIES_1 ON TRIP_HEADERS_1.TME_ID = TRIP_BODIES_1.TME_ID AND 
                      TRIP_HEADERS_1.THR_ID = TRIP_BODIES_1.THR_ID INNER JOIN
                      RTDEV.TNODED TNODED_1 ON TNODED_1.NID = TRIP_BODIES_1.CURRENT_NODE
-- PUT YOUR QUERY 2 HERE --
JOIN (SELECT     RTDEV.TRIP_HEADERS.TRIP_NAME, RTDEV.TRIP_BODIES.ARRIVAL_TIME, RTDEV.TRIP_BODIES.DEPARTURE_TIME
        FROM         RTDEV.TRIP_HEADERS INNER JOIN
                              RTDEV.TRIP_BODIES ON RTDEV.TRIP_HEADERS.TME_ID = RTDEV.TRIP_BODIES.TME_ID AND 
                              RTDEV.TRIP_HEADERS.THR_ID = RTDEV.TRIP_BODIES.THR_ID INNER JOIN
                              RTDEV.TNODED ON RTDEV.TNODED.NID = RTDEV.TRIP_BODIES.CURRENT_NODE
        WHERE     (RTDEV.TNODED.STRSHORTNAME = 'BER3') AND (RTDEV.TRIP_BODIES.TME_ID = 9860)) query2
-- AND PUT A JOIN CONDITION --
        ON TRIP_BODIES_1.DEPARTURE_TIME BETWEEN query2.ARRIVAL_TIME AND query2.DEPARTURE_TIME
WHERE     (TNODED_1.STRSHORTNAME = 'BER2') AND (TRIP_BODIES_1.TME_ID = 9860)