我试图查询飞机上的可用座位,这些座位沿着停靠,卸载和装载更多人的路线飞行。
我一直在尝试跨表查询,但是我遇到的问题是在单独的子查询中访问其他查询表的属性,这些子查询超出了其他子查询的范围。这可能与WITH ___ AS查询有关吗?
这里的前两个表是我正在使用的数据示例,希望能够产生所需的结果。下面的第一张表是为乘坐飞机的乘客提供的一系列连接,329,在start_airport,并在end_airport下车
start_airport | end_airport
---------------+------------
78 | 76
78 | 76
78 | 74
77 | 76
77 | 76
77 | 75
77 | 75
77 | 75
77 | 74
77 | 74
76 | 75
76 | 75
76 | 75
76 | 75
76 | 75
76 | 74
75 | 74
75 | 74
75 | 74
75 | 74
75 | 74
airplane | airport_id | airplane_size
----------+------------+-------------
329 | 78 | 67
329 | 77 | 67
329 | 76 | 67
329 | 75 | 67
329 | 74 | 67
我希望得到这个特定数据集的表格,其中可用座位在路线的每个站点更新:
airplane | airport_id | available_seating
----------+------------+------------------
329 | 78 | 64
329 | 77 | 57
329 | 76 | 55
329 | 75 | 59
您可以通过从connections
加入起始机场和终端机场的总和来解决您的问题。 SUM
分析函数可以为给定的表达式生成累积结果。
您还需要的唯一一件事就是id列,它指示了stoppages顺序的顺序。我刚刚使用ID
作为整数序列,如果你有一个日期列,它也可能是一个日期列。没有任何这样的列,就不可能确定正在运行的SUM的方向。
WITH st AS (
SELECT start_airport,
COUNT(*) AS cnt
FROM connections
GROUP BY start_airport
),en AS (
SELECT end_airport,
COUNT(*) AS cnt
FROM connections
GROUP BY end_airport
) SELECT airplane,
airport_id,
airplane_size - SUM( coalesce( st.cnt ,0) - coalesce(en.cnt,0) )
OVER( ORDER BY id --You should use the appropriate id column that determines order.
) as available_seating
FROM stops t2 left
JOIN st ON t2.airport_id = st.start_airport
LEFT JOIN en ON t2.airport_id = en.end_airport