【发布时间】:2022-01-10 18:29:57
【问题描述】:
从A镇、B镇、C镇或网上购买电影票的用户有两种。
我有以下表格:
位置:此表包含电影中心的位置
|--------------|------------|------------|
| Towns | latitude | longitude |
|--------------|------------|------------|
| Town_A | 72.92629 | -12.89272 |
| Town_B | 93.62789 | -83.10172 |
| Town_C | 68.92612 | -67.17242 |
|--------------|------------|------------|
用户:此表包含用户购买的历史,即在线或城镇。还包括用户购买时的纬度/经度。
|------------|------------|------------|--------------|
| user_id | latitude | longitude | Towns |
|------------|------------|------------|--------------|
| 1 | 21.89027 | -53.03772 | Town_A |
| 1 | 23.87847 | -41.78172 | Town_C |
| 1 | 39.62847 | -80.19892 | online |
| 1 | 77.87092 | -96.39242 | Town_A |
| 2 | 71.87782 | -38.03782 | online |
| 2 | 83.37847 | -62.78278 | Town_B |
| 3 | 89.81924 | -80.73892 | Town_B |
| 3 | 27.87282 | -18.39183 | Town_A |
|------------|------------|------------|--------------|
我想在用户购买时根据他的经纬度找到最近的城镇。决赛桌如下所示:
|------------|------------|------------|--------------|-----------------|
| user_id | latitude | longitude | Towns | nearest_town |
|------------|------------|------------|--------------|-----------------|
| 1 | 21.89027 | -53.03772 | Town_A | Town_B | <--- Town_B is near based on his lat/long (Irrespective of his purchase town)
| 1 | 23.87847 | -41.78172 | Town_C | Town_A | <--- Town_A is near based on his lat/long
| 1 | 39.62847 | -80.19892 | online | Town_Online |
| 1 | 77.87092 | -96.39242 | Town_A | Town_A |
| 2 | 71.87782 | -38.03782 | online | Town_Online |
| 2 | 83.37847 | -62.78278 | Town_B | Town_C |
| 3 | 89.81924 | -80.73892 | Town_B | Town_A |
| 3 | 27.87282 | -18.39183 | Town_A | Town_A |
|------------|------------|------------|--------------|-----------------|
SQL 查询 (Snowflake) 我的尝试:
With specific_location as
(
select user_id,
latitude,
longitude,
case when Towns in ('Town_A','Town_B','Town_C') then 'Town' else 'Town_Online' end as purchase_in
from Locations
)
select *,
case when purchase_in = 'Town' then
(select Towns from Location qualify row_number() over (order by haversine(user.latitude,user.longitude,location.latitude,location.longitude))=1)
else purchase_in
end as nearest_town
from specific_location
我收到一个错误:syntax error unexpected 'when' and unexpected 'else'
【问题讨论】:
标签: sql snowflake-cloud-data-platform window-functions