sql-server - SQL Server:仅在两个值相同的情况下选择行一次
问题描述
我正在研究IP2Location提供的开源和免费数据库,其中列出了来自互联网的大量 IP 地址。
你可以从这里下载。
我的主要兴趣不是 IP 地址:我希望每个国家/地区的每个城市都有 1 个地理坐标。
我现在的查询返回双倍:
WITH cte AS
(
-- Let's pass rows that have the same latitude and longitude
SELECT *, ROW_NUMBER() OVER (PARTITION BY latitude, longitude
ORDER BY latitude, longitude) AS rn
FROM ip2location_db11
-- Avoid rows without city name
where city_name != '-'
)
SELECT
-- These are the only columns I'm interested in from the whole ip2location_db11 database
ROW_NUMBER() OVER (ORDER BY country_code desc,city_name desc) as countdown_order,
latitude,longitude,city_name,country_code
FROM cte
-- Let's take the first row where latitude and longitude are the same
WHERE rn = 1
-- I want to order results by city name
order by countdown_order desc
这很烦人:
每个城市一个经纬度的一排就可以了:我只想在地图上放一个大头针
解决方案
我不知道,您的第一列 ( countdown_order
) 是否有任何意义,或者只是该行的唯一标识符......
无论如何,如果您只想拥有一个带有一对坐标的城市/国家,您可能应该使用GROUP BY
聚合AVG()
函数来平均给定城市的坐标......
SELECT AVG(latitude) AS latitude, AVG(longitude) AS longitude, city_name, country_code
FROM ip2location_db11
GROUP BY country_code, city_name
ORDER BY country_code, city_name
推荐阅读
- python - 为什么我的损失价值如此巨大?在 TensorFlow 上运行 MLP
- api - 通过 API 访问来自我的 Google Workspace 成员的所有电子邮件
- python - 对于 pandas 数据框中的一列,计算当前行前第 4、第 8 和第 12 行的列值的平均值?
- r - 根据打开和关闭日期生成分组时间序列
- node.js - 无法让 Azure 配置管理器通过 NPM/Nodejs 运行
- javascript - 手动输入输入框触发事件,但在 javascript 中以编程方式设置值未触发事件
- python - 如何使用正则表达式匹配重复模式(它们之间有随机文本)?
- javascript - 引导日期选择器弹出未显示选定日期
- javascript - 什么是调用使用来自 v-for 中的信息发出 axios 请求的函数的好方法?
- optimization - GEKKO - 矩阵形式的 MINLP - 使用 m.axb() 的错误