首页 > 解决方案 > 有一个 airbnb 数据集,需要使用 join-function 确定哪些主机在同一位置有多个公寓

问题描述

根据 airbnb 数据集,我需要找出哪些主机在同一位置有多个房间。

我有两张桌子:airbnb 和 airbnb_locations

airbnb 表的前六行如下所示:

host_id    room_id    latitude    longitude
2536       2318       47.61       -122.29
35749      4291       47.68       -122.31
8993       5682       47.52       -122.35
14942      6606       47.65       -122.33
30559      9419       47.55       -122.31
30832      9460       47.60       -122.32

airbnb_locations 表的前六行如下所示:

room_id    latitude    longitude
2318       47.61       -122.29
4291       47.68       -122.31
5682       47.52       -122.35
6606       47.65       -122.33
9419       47.55       -122.31
9460       47.60       -122.32

所以表之间的唯一区别是 host_id 属性。

这是我的第一次尝试:

select distinct t1.host_id, t1.room_id, t1.latitude, t1.longitude
from airbnb t1 inner join airbnb_locations t2
where t1.latitude = t2.latitude
and t1.longitude = t2.longitude
and t1.room_id <> t2.room_id

这段代码的问题在于它还会产生属于同一位置的不同主机的房间。我曾尝试按主机对房间进行分组,但由于某种原因,这给了我错误的结果。

解决方案可能是将 host_id 属性添加到 airbnb_locations 然后:

select distinct t1.host_id, t1.room_id, t1.latitude, t1.longitude
from airbnb t1 inner join airbnb_locations t2
where t1.host_id = t2.host_id
and t1.latitude = t2.latitude
and t1.longitude = t2.longitude
and t1.room_id <> t2.room_id

但是我留下了两张相同的表,我不确定这是否是本练习的重点。所以我很好奇我是否错过了基于使用连接函数的两个初始表来解决问题的明显解决方案?

标签: sqlapache-spark-sqlinner-join

解决方案


我想你想要聚合:

select a.host_id, a.latitude, a.longitude
from airbnb a
group by a.host_id, a.latitude, a.longitude
having count(*) > 1;

这实际上返回了位置。如果您真的只想要主机,那么这是一个非常罕见的时间,select distinct适合group by

select distinct a.host_id
from airbnb a
group by a.host_id, a.latitude, a.longitude
having count(*) > 1;

推荐阅读