将选定的 table 连接到交叉连接的 table

Joining a selected table to a cross joined table

我有一个 table、flight_schedule,它由一堆航段组成。下面我有一个 Terradata SQL 查询,它创建了芝加哥和丹佛之间的两个航段行程列表。即每一行都有两个航班,最终将乘客从芝加哥带到丹佛。例如,第一行包含从芝加哥到奥马哈的航程以及从奥马哈到丹佛的后续航程的航班信息。此查询工作得很好。

SELECT A.flt_num, A.dprt_sta_cd, A.arrv_sta_cd, A.sch_dprt_dtml, A.sch_arrv_dtml, 
B.flt_num, B.dprt_sta_cd, B.arrv_sta_cd, B.sch_dprt_dtml, B.sch_arrv_dtml
FROM 
flight_schedule A 
CROSS JOIN 
flight_schedule B
WHERE
A.dprt_sta_cd = 'Chicago' AND
B.arrv_sta_cd = 'Denver' AND
A.arrv_sta_cd = B.dprt_sta_cd AND
A.sch_arrv_dtml < B.sch_dprt_dtml
ORDER BY B.sch_arrv_dtml;

我有另一个 table,flight_seat_inventory,其中包含每个航班号在不同客舱的可用座位。下面的查询汇总了每个航班号的可用座位总数。这个查询也是A-OK.

SELECT flt_num, SUM(seat_cnt) as avail_seats
FROM flight_seat_inventory
GROUP BY flt_num;

我想将这两个查询与 LEFT JOIN 组合两次,以便每个航班都有相应的 avail_seats 值。我该怎么做?

为了更加清晰,我想我想要的 Select 声明如下所示:

SELECT A.flt_num, A.dprt_sta_cd, A.arrv_sta_cd, A.sch_dprt_dtml, A.sch_arrv_dtml, C.avail_seats
B.flt_num, B.dprt_sta_cd, B.arrv_sta_cd, B.sch_dprt_dtml, B.sch_arrv_dtml, D.avail_seats

flight_schedule 很大,所以我怀疑在 CROSS JOIN 之后执行 LEFT JOIN 会更有效率。同样,使用 Teradata SQL.

谢谢!

在执行 LEFT JOIN 之前,我需要使用 WITH 命令将第二个座位查询声明为临时 table:

WITH tempSeatsTable AS (
SELECT flt_num, SUM(seat_cnt) as avail_seats  
FROM flight_seat_inventory
GROUP BY flt_num    
)

SELECT 
A.flt_num, A.dprt_sta_cd, A.arrv_sta_cd, A.sch_dprt_dtml, A.sch_arrv_dtml, C.avail_seats
B.flt_num, B.dprt_sta_cd, B.arrv_sta_cd, B.sch_dprt_dtml, B.sch_arrv_dtml, D.avail_seats

FROM 
flight_schedule A 
CROSS JOIN 
flight_schedule B
LEFT JOIN
tempSeatsTable C
ON A.flt_num = C.flt_num
LEFT JOIN
tempSeatsTable D
ON B.flt_num = D.flt_num

WHERE
A.dprt_sta_cd = 'Chicago' AND
B.arrv_sta_cd = 'Denver' AND
A.arrv_sta_cd = B.dprt_sta_cd AND
A.sch_arrv_dtml < B.sch_dprt_dtml
ORDER BY B.sch_arrv_dtml;