我正在尝试使用SQL Server的一些地理功能来确定客户最近的10个分支机构是什么。这让我得到了我想要的一个客户:
DECLARE @me GEOGRAPHY
DECLARE @HH NVARCHAR(50)
SELECT @Me = CustProspLoc, @HH = HHKEY FROM Customers
SELECT DISTINCT TOP(10) @HH AS CustOmer, BranchNum, CONVERT(DECIMAL(10,1), (BranchLoc.STDistance(@me)) / 1609.344) AS Miles, BranchLoc.STDistance(@me)
FROM
BranchLocations
WHERE CONVERT(DECIMAL(10,1), (BranchLoc.STDistance(@me)) / 1609.344) < 25 -- less than this many miles
ORDER BY Miles
结果是这样的:
Customer BranchNum Miles
------------------ --------- ---------------------------
20192 14 1.8
20192 145 4.4
20192 193 5.3
20192 7 6.0
20192 17 7.4
20192 8 7.6
20192 3 8.7
20192 2 9.3
20192 9 9.8
20192 1 10.0
但我得到的只是那个客户的结果......如何才能为Customers表中的所有客户提供?
答案 0 :(得分:1)
尝试使用此查询
Select * from(
SELECT row_number() over(partition by hhkey order by miles) as rownum, HHKEY as CustOmer, BranchNum, CONVERT(DECIMAL(10,1), (BranchLoc.STDistance(CustProspLoc)) / 1609.344) AS Miles, BranchLoc.STDistance(CustProspLoc)
FROM
BranchLocations,Customers
WHERE CONVERT(DECIMAL(10,1), (BranchLoc.STDistance(CustProspLoc)) / 1609.344) < 25 -- less than this many miles
ORDER BY Miles) as t1 where t1.rownum <= 10