如何从子查询引用函数结果列?

时间:2018-04-22 18:49:06

标签: sql postgresql

我正在尝试提出一个查询,该查询计算按年分组的行,我将从TIMESTAMP和airline_id获取。到目前为止,我已经想出了这个:

SELECT airline_id, extract(year from departure)::integer as year,
(SELECT count(*) FROM tickets AS t2 LEFT JOIN flights AS f2 ON t2.flight_id = f2.flight_id WHERE extract(year from f2.departure) = year AND f2.airline_id = f.airline_id)
FROM tickets AS t
LEFT JOIN flights AS f ON t.flight_id = f.flight_id
GROUP BY airline_id, year
ORDER BY airline_id ASC, year ASC;

似乎它会正常工作,除非它抛出此错误:

  

错误:列“年”不存在

我尝试将其引用为:

SELECT airline_id, extract(year from departure)::integer as year,
(SELECT count(*) FROM tickets AS t2 LEFT JOIN flights AS f2 ON t2.flight_id = f2.flight_id WHERE extract(year from f2.departure) = t.year AND f2.airline_id = f.airline_id)
FROM tickets AS t
LEFT JOIN flights AS f ON t.flight_id = f.flight_id
GROUP BY airline_id, year
ORDER BY airline_id ASC, year ASC;

但它做同样的事情。您也无法再次调用该函数,因为

  

错误:子查询使用来自外部查询的未分组列“f.departure”

那么我该如何从子查询中引用“year”列?

1 个答案:

答案 0 :(得分:0)

让我们从这个问题开始:

SELECT f.airline_id,  -- I speculate that the airline comes from the flights table
       extract(year from f.departure) as year,
       COUNT(*)
FROM tickets t LEFT JOIN
     flights f 
     ON t.flight_id = f.flight_id
GROUP BY f.airline_id, year
ORDER BY airline_id ASC, year ASC;

它能做到你想要的吗?您的子查询似乎没有任何用处。