简体   繁体   English

SQL按多列中的值对分组并消除相同的元组

[英]SQL grouping by value pairs in multiple columns and eliminating identical tuples

I have a database table containing flights. 我有一个包含航班的数据库表。 (The origin/destinations are in IATA airport codes.) (起源/目的地在国际航空运输协会机场代码中。)

id   origin   destination
1    AMS      BON
2    BON      AMS
3    EIN      GDN
4    GDN      EIN
5    EIN      GDN
6    AMS      AGP

I am trying to find the number of the flights between each two airports, irrespective of the direction of the flight. 我试图找出每两个机场之间的航班数量,而不管飞行方向如何。 So I am looking for this result: 所以我正在寻找这个结果:

origin    destination    count
AMS       BON            2
EIN       GDN            3
AMS       AGP            1

What I have so far is this query: 到目前为止,我有这个查询:

SELECT c.origin, c.destination, count(c.origin) as count FROM 
(
SELECT a.origin as origin, a.destination as destination FROM Flights a 
UNION ALL SELECT b.destination as origin, b.origin as destination FROM Flights b 
) c 
GROUP BY origin, destination;

Which gives the following result: 得到以下结果:

origin    destination    count
AMS       BON            2
BON       AMS            2
EIN       GDN            3
GDN       EIN            3
AMS       AGP            1

So the problem is that there are duplicate tuples. 因此,问题在于有重复的元组。 How do I eliminate those? 如何消除这些?

It seems similar to this question, but not similar enough I'm afraid. 似乎与此问题相似,但恐怕不够相似。 Eliminate tuples with reverse relation and no primary Key 消除具有反向关系且没有主键的元组

An easier approach is to use least() and greatest() : 一种更简单的方法是使用least()greatest()

SELECT least(origin, destination) as city1,
       greatest(origin, destination) as city2, count(*) as cnt
FROM Flights f
GROUP BY least(origin, destination), greatest(origin, destination)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM