GROUP BY子句中的SQL Geography数据类型列

时间:2012-04-12 10:01:53

标签: sql sql-server tsql group-by sqlgeography

我正在使用SQL Server并创建一个脚本,该脚本将从我的数据库中获取工作者的地理位置。脚本如下。

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 .....

问题是我想在脚本中添加GROUP BY w.display_name, w.geo_location,因为显示了重复的记录。向group by子句添加了具有数据类型geography的列会导致抛出错误。

我添加它时抛出的错误是:

  

“地理”类型无法比较。它不能在GROUP BY子句中使用。

有解决方法吗?我无法将w.geo_location转换为地理数据类型中所需的VARCHAR

2 个答案:

答案 0 :(得分:5)

如果您想继续使用group by语法,可以将geo列转换为text并再返回:

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()

答案 1 :(得分:4)

您可以使用row_number()这样的内容。

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

结果:

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