需要帮助订购这些结果

时间:2013-08-14 00:09:52

标签: sql-server tsql

我有这个查询,它运行正常,但我想先根据最接近的结果进行排序:

    SELECT DISTINCT Name, Address, City, State, Zip FROM Clinics WHERE ZIP IN 
   (SELECT h.zipcode FROM zipcodes 
    g JOIN zipcodes h on g.zipcode <> 
    h.zipcode AND g.zipcode = '32244' AND h.zipcode <> '32244'
     WHERE g.GeogCol1.STDistance(h.GeogCol1)<=(100 * 1609.344)) 
    UNION ALL SELECT DISTINCT Name, Address, City, State, Zip 
    FROM Clinics WHERE ZIP = '32244'

我试过了:

SELECT DISTINCT Name, Address, City, State, Zip FROM Clinics 
WHERE ZIP IN (SELECT h.zipcode FROM zipcodes 
g JOIN zipcodes h on g.zipcode <> 
h.zipcode AND g.zipcode = '32244' AND h.zipcode <> '32244'
WHERE g.GeogCol1.STDistance(h.GeogCol1)<=(100 * 1609.344)) 
UNION ALL SELECT DISTINCT Name, Address, City, State, Zip
FROM Clinics WHERE ZIP = '32244' 
order by g.GeogCol1.STDistance(h.GeogCol1) DESC

但它给了我一个错误:

 找不到列“g”或用户定义的函数或聚合“g.GeogCol1.STDistance”,或者名称不明确。

我这样做了吗?

1 个答案:

答案 0 :(得分:4)

首先你需要确定距离:

SELECT h.zipcode, (g.GeogCol1.STDistance(h.GeogCol1) / 1609.344) dist
  FROM dbo.zipcodes h CROSS JOIN dbo.zipcodes g
 WHERE g.zipcode = '32244'

这会将所讨论的邮政编码与所有邮政编码(包括其自身)配对。 (我将联接包含在相同的邮政编码中,因为这样可以避免以后必须执行UNION。)

下一步是过滤距离:

WITH ZipPairs AS(
  SELECT h.zipcode, (g.GeogCol1.STDistance(h.GeogCol1) / 1609.344) dist
    FROM dbo.zipcodes h CROSS JOIN dbo.zipcodes g
   WHERE g.zipcode = '32244'
), CloseZips AS(
  SELECT *
    FROM ZipPairs
   WHERE Dist < 100*1609.344
)
SELECT * FROM CloseZips;     

之后,您可以加入诊所并按距离排序:

WITH ZipPairs AS(
  SELECT h.zipcode, (g.GeogCol1.STDistance(h.GeogCol1) / 1609.344) dist
    FROM dbo.zipcodes h CROSS JOIN dbo.zipcodes g
   WHERE g.zipcode = '32244'
), CloseZips AS(
  SELECT *
    FROM ZipPairs
   WHERE Dist < 100*1609.344
)
SELECT C.*,Z.Dist
  FROM dbo.Clinics AS C
  JOIN CloseZips Z
    ON C.Zip = Z.zipcode
 ORDER BY Z.Dist;