sql - 有一个 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
但是我留下了两张相同的表,我不确定这是否是本练习的重点。所以我很好奇我是否错过了基于使用连接函数的两个初始表来解决问题的明显解决方案?
解决方案
我想你想要聚合:
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;
推荐阅读
- php - 在 PHP 中避免空值时,我可以重新实现 isset 吗?
- c# - 通过表单发布的数据挂起应用程序
- travis-ci - 使用 Travis CI 发布到 NPMJS
- angular - 使用自定义指令值选择性地显示表单元素
- aws-lambda - 在 AWS Lambda 中增加重试次数
- python - 无法在 Windows 上使用 winsound 播放 .mp3 文件
- powershell - 处理列表时的 Powershell 错误处理
- c# - 从 TextBox 访问值
- c# - C# 整数?参数-数据为空。不能对 Null 值调用此方法或属性
- google-chrome - 浏览器会根据哪些标准考虑使用“application/x-www-form-urlencoded”作为内容类型?