Tricky sql与Sql Geometry字段不同

时间:2012-12-06 20:43:10

标签: sql sql-server geometry distinct

我有一个与Sql Geometry类型不兼容的sql语句,因此我正在尝试对其进行修改以使其正常工作。

它的基本要点是这样的:

Select distinct A,B,C,D,SHAPE FROM TABLE1 UNION SELECT A,B,C,D,SHAPE FROM TABLE2

因此,对两个不同(但相似)表的复杂不同语句的结果进行了联合。

问题是SQL Geometry类型(SHAPE字段)不能包含在不同的语句中,因为它不是类似的类型。

我可以从参与联合的两个子查询中删除SHAPE字段。但我希望在解析这些子查询后将其恢复。 如果我知道A列的值,我可以得到SHAPE字段。

所以我的问题是:我如何从两个子查询中的distinct语句中删除一个字段,然后通过加入返回结果集中的该字段(以及其余字段)它在另一列(A)?

3 个答案:

答案 0 :(得分:2)

您可以强制转换为VARBINARY(MAX),然后强制转换。

create table tbl1 ( ID int, a int, b char(3), d geometry );
create table tbl2 ( ID int, a int, b char(3), d geometry, other float );
insert tbl1 (ID, a, b, d) values
    (1, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)),
    (2, 3, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)),
    (3, 4, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)),
    (4, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 250 0, 150 150, 0 150, 0 0))', 0)),
    (5, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 350 0, 150 150, 0 150, 0 0))', 0))
insert tbl2 (ID, a, b, d) values
    (6, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0)), -- same as tbl1.ID=1
    (7, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 950 0, 150 150, 0 150, 0 0))', 0)),
    (8, 2, 3, geometry::STGeomFromText('POLYGON ((0 0, 350 0, 150 150, 0 150, 0 0))', 0)); -- same as tbl1.ID=5

SELECT A, B, cast(c as geometry) c
FROM
(
    Select A,B,cast(D as varbinary(max)) c FROM tbl1
    UNION
    SELECT A,B,cast(D as varbinary(max)) FROM tbl2
) X;

答案 1 :(得分:0)

CREATE VIEW GeometryView1 AS
  SELECT A,B,C,D,SHAPE AS tabId FROM TABLE1 
  UNION SELECT A,B,C,D,SHAPE FROM TABLE2;

CREATE VIEW GeometryView2 AS
  SELECT DISTINCT A,B,C,D FROM (
  SELECT A,B,C,D AS tabId FROM TABLE1 
  UNION SELECT A,B,C,D FROM TABLE2) x;

SELECT DISTINCT v2.A,v2.B,v2.C,v2.D,v1.SHAPE FROM GeometryView2 v2 , GeometryView1 v1
WHERE v2.A=v1.A AND v2.B=v1.B AND v2.C=v1.C AND v2.D=v1.D 

答案 2 :(得分:0)

这会有用吗?

with cte as (
Select distinct A,B,C,D FROM TABLE1
)
select c.A,c.B,c.C,c.D,t.SHAPE 
FROM cte as c
inner join TABLE1 as t
   on c.A = t.A
UNION 
SELECT A,B,C,D,SHAPE FROM TABLE2