SQL Geography data type column in GROUP BY clause

寵の児 提交于 2020-01-24 05:49:39

问题


I'm using SQL Server and creating a script which will get the workers geographical location out of my database. The script is below.

SELECT w.display_name, w.geo_location
FROM jobs j WITH(NOLOCK)
INNER JOIN workers w WITH(NOLOCK) ON w.worker_id = j.worker_id
WHERE .....

The problem is that I want to add GROUP BY w.display_name, w.geo_location to the script as there are duplicate records being shown. Added a column with the data type geography to a group by clause causes an error to be thrown.

The error being thrown when I add this in is:

The type "geography" is not comparable. It cannot be used in the GROUP BY clause.

Is there a way around this? I cannot convert w.geo_location to a VARCHAR as it is needed in the geography data type.


回答1:


You can use row_number() something like this.

declare @g geography;
set @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);

declare @T table
(display_name varchar(10), geo_location geography)

insert into @T values ('1', @g)
insert into @T values ('1', @g)
insert into @T values ('1', @g)

insert into @T values ('2', @g)
insert into @T values ('2', @g)

select display_name, geo_location
from 
  (
    select *,
           row_number() over(partition by display_name, geo_location.ToString() order by (select 0)) as rn
    from @T
  ) as T
where rn = 1

Result:

display_name geo_location
------------ --------------------------------------------------------------------------------
1            0xE610000001148716D9CEF7D34740D7A3703D0A975EC08716D9CEF7D34740CBA145B6F3955EC0
2            0xE610000001148716D9CEF7D34740D7A3703D0A975EC08716D9CEF7D34740CBA145B6F3955EC0



回答2:


If you want to continue to use the group by syntax you can convert the geo column to text and back again:

SELECT w.display_name, geography::STGeomFromText(w.geo_location.STAsText(), 4326) as Location
FROM jobs j WITH(NOLOCK)
INNER JOIN workers w WITH(NOLOCK) ON w.worker_id = j.worker_id
WHERE .....
GROUP BY w.display_name, w.geo_location.STAsText()


来源:https://stackoverflow.com/questions/10121403/sql-geography-data-type-column-in-group-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!