首页 > 解决方案 > 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

这很烦人:

在此处输入图像描述

每个城市一个经纬度的一排可以了:我只想在地图上放一个大头针

标签: sql-serverselectsubquerycommon-table-expression

解决方案


我不知道,您的第一列 ( 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

推荐阅读