如何解决PostgreSQL-如何查找热门路线两列相同的记录?
我有一个简单的Ruby On Rails应用程序,可以管理旅程。这是我存储在数据库中的数据的示例:
id | origin | destination | ...
1 | London,UK | Prague,CZ | ...
2 | Paris,FR | Berlin,GE | ...
3 | Berlin,GE | Munich,GE | ...
4 | Berlin,GE | Moscow,RU | ...
5 | Rome,IT | Florence,IT | ...
6 | London,CZ | ...
7 | Paris,GE | ...
8 | Paris,GE | ...
我想找到最热门的旅程,所以所需的输出是这样的:
Paris,GE | 3x
London,CZ | 2x
Berlin,GE | 1x
Berlin,RU | 1x
Rome,IT | 1x
我该如何实现?我有一个30万行程的数据库,对于大多数行程,我还存储了经纬度坐标-但是在这种情况下,不确定以字符串形式搜索起点和终点还是通过协调来搜索字段是否更好。 / p>
提前谢谢!
解决方法
您可以汇总,计数和排序:
select origin,destination,count(*) cnt
from mytable
group by origin,destination
order by cnt desc
然后,您可以使用limit
子句控制查询返回的路由数。假设您要选择5条最频繁的路线,然后:
select origin,destination
order by cnt desc
limit 5
但是请注意,这并未考虑潜在的联系。如果您对此感兴趣,那么解决方案取决于您的Postgres版本。在最新版本(Postgres 13)中:
select origin,destination
order by cnt desc
fetch first 5 rows with ties
在早期版本中:
select origin,cnt
from (
select origin,count(*) cnt,rank() over(order by count(*) desc) rn
from mytable
group by origin,destination
) t
where rn <= 5
order by cnt desc
,
根据您当前的数据库设计得出的答案:
Trip.select('origin,count(*) as trips_count')
.group(:origin,:destination).order('trips_count desc')
如果要在查询中包括航空公司,则可以使用array_agg
function:
Trip.select('origin,count(*) as trips_count,array_agg(distinct(airline)) as airlines')
.group(:origin,:destination).order('trips_count desc')
我建议将origin
和destination
列移到自己的表中,例如routes
表中,并将trips
表中的这些列替换为{{1 }}。您还可以在route_id
表上实现trips_count
counter_cache,只需按该列排序即可获得最受欢迎的路线。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。