我不是数据库专家,甚至不知道如何处理这个问题。我相信对于那些了解TSQL的人来说很简单,并欢迎一些见解。
我有一个包含邮政编码和Eastings和Northings的数据库。例如:
Postcode Easting Northing
---------------------------
HR74DW 365601 254668
B129DB 407863 284797
我想提供东向和北向值并返回最接近的单个记录(即匹配的邮政编码)。所以,像:
SELECT TOP 1 Postcode
FROM [PostcodeAddresses].[dbo].[FullPostcodeEastingNorthing]
WHERE Easting (IS CLOSEST TO) 417940
AND Northing (IS CLOSEST TO) 284824.
我正在使用.NET MVC 4,所以如果有人知道如何使用LINQ这样做,它也会非常方便(但我仍然对TSQL很满意。
非常感谢提前。
答案 0 :(得分:0)
试试这个:
WITH CTE
AS
(
SELECT
postcode,
ABS(Easting - 417940) AS MinEasting,
ABS(Northing - 284824) AS MinNorthing
FROM FullPostcodeEastingNorthing
)
SELECT postcode
FROM FullPostcodeEastingNorthing
WHERE ABS(Easting - 417940 ) = (SELECT MIN(MinEasting)
FROM CTE)
AND ABS(Northing - 284824) = (SELECT MIN(MinNorthing)
FROM CTE);
请在此处查看:
答案 1 :(得分:0)
我正在使用@ w0lf的建议,因为它运行良好且数据库不是很大且查询数量很少 - 因此完全扫描的小延迟是可以接受的。
这是我用的邮政编码的例子:
SELECT [Postcode], [Easting], [Northing]
FROM [PostcodeAddresses].[dbo].[FullPostcodeEastingNorthing]
WHERE Postcode = 'GU147NL'
Postcode Easting Northing --------------------------- GU147NL 486871 156016
以下是我使用@ w0lf的建议返回邮政编码的方法。你可以看到东方和北方与上面的不一样,但是很接近,它会返回正确的邮政编码。
SELECT TOP 1 Postcode
FROM [PostcodeAddresses].[dbo].[FullPostcodeEastingNorthing]
ORDER BY (easting-486860)*(easting-486860)
+ (northing-156007)*(northing-156007)
ASC
Postcode -------- GU147NL
谢谢@ w0lf!