SQL Server:仅在两个值相同的情况下,SELECT行仅一次

时间:2018-07-27 11:53:40

标签: sql-server select subquery common-table-expression

我正在使用IP2Location提供的 OpenSource 免费数据库,其中列出了来自互联网的大量IP地址。

您可以从here下载它。

我的主要兴趣不是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

这很烦人:

enter image description here

在每个城市中每行具有一个纬度经度的行就可以了:我只想在地图上放一个图钉

3 个答案:

答案 0 :(得分: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 != '-'          
)
,columnsneeded as (

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
)

Select countdown_order,latitude,longtitude,city_name,country_code 
from(
Select *,ROW_NUMBER() over(partition by city_name order by countdown_order) as rn1 from columnsneeded
)x where rn1 = 1
-- I want to order results by city name
order by countdown_order desc

答案 1 :(得分:1)

我不知道您的第一列(countdown_order)是否有意义,还是该行的唯一标识符...

无论如何,如果您只想拥有一个带有一对坐标的城市/国家,则可能应该将GROUP BYAVG()聚合函数一起使用以平均给定坐标城市...

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

答案 2 :(得分:0)

您需要做的就是使用ROW_NUMBER按城市划分(并按任何顺序排列:)),并仅在外部查询中使用等于1的那些(您必须将其包装)。试试这个:

SELECT countdown_order,latitude,longitude,city_name,country_code FROM (
    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,
    ROW_NUMBER() OVER (PARTITION BY city_name ORDER BY latitude) rnTofilter,
    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
) a WHERE rnToFilter = 1
order by countdown_order desc