计算多列中的不同值

时间:2015-06-23 20:45:24

标签: sql postgresql aggregate-functions

给出以下架构:

id departure arrival
0  BOS       LAX
1  SFO       SEA
2  MIA       LAX
3  RDU       BOS
4  JFK       DEN
5  LAX       SEA

我需要计算每个机场的总发生次数。例如,BOS应为2(一次出发和一次到达)。

我可以通过两个单独的查询来执行此操作:

SELECT departure, COUNT(*) FROM legs
GROUP BY departure ORDER BY COUNT(departure) DESC

SELECT arrival, COUNT(*) FROM legs
GROUP BY arrival ORDER BY COUNT(arrival) DESC

但我无法弄清楚或找到一种方法在一个查询中执行此操作。我希望得到以下内容:

airport count
BOS     2
LAX     2
SEA     2
JFK     1

2 个答案:

答案 0 :(得分:4)

使用union执行此操作:

select departure as airport, count(*) as count
from (select departure from legs
      union all
      select arrival from legs)t
group by departure

答案 1 :(得分:0)

在两个单独的聚合上使用FULL [OUTER] JOIN

SELECT airport, COALESCE(d.ct, 0) + COALESCE(a.ct, 0) AS "count"
FROM  (
   SELECT departure AS airport, count(*) AS ct
   FROM   legs
   GROUP  BY 1
   ) d
FULL JOIN (
   SELECT arrival AS airport, count(*) AS ct
   FROM   legs
   GROUP  BY 1
   ) a USING (airport)
ORDER  BY "count" DESC, airport;

通过这种方式,您可以轻松返回到达和离开的其他列,如果您想要选择某些机场,则可以使用基表上的索引。

最近的相关答案: