[英]Counting distinct values from multiple columns
Given the following schema: 给定以下架构:
id departure arrival
0 BOS LAX
1 SFO SEA
2 MIA LAX
3 RDU BOS
4 JFK DEN
5 LAX SEA
I need to count the total occurrences of each airport. 我需要计算每个机场的总数。 For example, BOS should be 2 (one departure and one arrival).
例如,BOS应该为2(一次起飞一次到达)。
I'm able to do this with two separate queries: 我可以通过两个单独的查询来做到这一点:
SELECT departure, COUNT(*) FROM legs
GROUP BY departure ORDER BY COUNT(departure) DESC
and 和
SELECT arrival, COUNT(*) FROM legs
GROUP BY arrival ORDER BY COUNT(arrival) DESC
but I haven't been able to figure out or find a way to do it in one query. 但我无法在一个查询中找到解决办法。 I'd like to have something like the following:
我想要以下内容:
airport count
BOS 2
LAX 2
SEA 2
JFK 1
Do it with union
: 用
union
:
select departure as airport, count(*) as count
from (select departure from legs
union all
select arrival from legs)t
group by departure
Use a FULL [OUTER] JOIN
on two separate aggregates: 在两个单独的聚合上使用
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;
This way you can easily return additional columns for arrival and departure, and you can use indexes on the base table if you should want to select certain airports. 这样,您可以轻松地返回到达和离开的其他列,并且如果您想选择某些机场,则可以在基表上使用索引。
Recent related answer: 最近相关答案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.