简体   繁体   中英

Select all records using variables

I'm trying to use some of the geography features of SQL Server to figure out what are a customer's closest 10 branch offices. This gets me what I want for one customer:

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

And the result is like this:

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

But all I get is results for that one Customer...how can I get it for all the customers in the Customers table?

Try using this query

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM