group by子句嵌套选择语句

时间:2014-10-30 23:00:57

标签: sql sql-server sql-server-2012

我很难让这段代码工作,我想做的是选择多个列名,然后将结果分组到同一个表中的另外两列。

但我似乎无法使语法正确,所以任何拥有更多sql服务器经验的人都可以帮助我解决这个问题。

我正在寻找的是根据纬度,经度返回非重复结果

实际代码

SELECT    [CityName]                         AS CityName,  
          ISNULL(NULLIF([CountyName],''),'') AS CountyName,
          [CityLatitude]                     AS Latitude,
          [CityLongitude]                    AS Longitude
    FROM [dbo].[tblCityLatitudeLongitudes]
          WHERE [CountryName] = @Country

    ORDER by [CityName] ASC
    OFFSET @OffSet ROWS 
FETCH NEXT 10 ROWS ONLY; 

我尝试了其他各种方法,下面是我的最后一次尝试,但仍然会抛出错误

SELECT    a.CityName                       AS CityName,  
          ISNULL(NULLIF(a.CountyName,''),'')  AS CountyName,
          a.CityLatitude                   AS Latitude,
          a.CityLongitude                  AS Longitude 
          FROM
 (SELECT b.CityLatitude,b.CityLongitude
 FROM  tblCityLatitudeLongitudes b
 WHERE b.CountryName = 'united kingdom'
GROUP BY b.CityLatitude,b.CityLongitude) a   

错误

Msg 207, Level 16, State 1, Line 24
Invalid column name 'CityName'.
Msg 207, Level 16, State 1, Line 25
Invalid column name 'CountyName'.
Msg 207, Level 16, State 1, Line 25
Invalid column name 'CountyName'.    

2 个答案:

答案 0 :(得分:1)

SELECT CityName
      ,CountyName
      ,Latitude
      ,Longitude
FROM (
    SELECT    [CityName]                         AS CityName,  
              ISNULL(NULLIF([CountyName],''),'') AS CountyName,
              [CityLatitude]                     AS Latitude,
              [CityLongitude]                    AS Longitude,
              ROW_NUMBER() OVER (PARTITION BY [CityLatitude],[CityLongitude] ORDER BY (SELECT NULL))rn 
    FROM [dbo].[tblCityLatitudeLongitudes]
    WHERE [CountryName] = @Country
    )A
WHERE rn = 1
ORDER by [CityName] ASC
OFFSET @OffSet ROWS 
FETCH NEXT 10 ROWS ONLY; 

答案 1 :(得分:1)

您可以在其他列上进行分组,并获得最大纬度和经度。

  SELECT    a.CityName                       AS CityName,  
         ISNULL(NULLIF(a.CountyName,''),'')  AS CountyName,
      Max(a.CityLatitude    )               AS Latitude,
      Max(a.CityLongitude      )            AS Longitude 
      FROM
    tblCityLatitudeLongitudes a
    WHERE a.CountryName = 'united kingdom'
    GROUP BY CityName, ISNULL(NULLIF(a.CountyName,''),'') 
ORDER by [CityName] ASC
OFFSET @OffSet ROWS 
FETCH NEXT 10 ROWS ONLY;