我有一个包含这些示例行的表:
CouponID ShopID ShopLongitude ShopLatitude 365 1881 55,5574105 9,9613295 365 23550 55,5510846 9,9936818 365 33550 55,6220936 10,0663895 365 33551 55,5573436 9,9611765 366 1881 55,5574105 9,9613295 366 23550 55,5510846 9,9936818 367 1881 55,5574105 9,9613295 533 1881 55,5574105 9,9613295 533 23550 55,5510846 9,9936818 533 33550 55,6220936 10,0663895 533 33551 55,5573436 9,9611765 354 1881 55,5574105 9,9613295 354 23550 55.5510846 9,9936818 354 33550 55,6220936 10,0663895 354 33551 55,5573436 9,9611765
我希望得到每张CouponID
最近的ShopID我已经有了查询:
SELECT CouponID, MIN (dbo.DistanceBetween (53.54613,9.98537,ShopLatitude,ShopLongitude)) as distance
FROM Table
GROUP BY CouponID
ORDER BY CouponID, distance ASC
为每张优惠券输出CouponID和ShopID的最小距离:
CouponID distance 354 0,778524633472375 365 0,778524633472375 366 0,778524633472375 367 2,02548179145764
在LINQ中语句如下:
var coupon = (from c in dbContext.table
group c by c.CouponID into cgrp
select new
{
CouponID = cgrp.Key,
Distance = cgrp.Min(c => DistanceBetween(latitude, longitude, c.ShopLatitude, c.ShopLongitude))
})
.OrderBy(c => c.CouponID).ThenBy(c => DistanceBetween(latitude, longitude, c.ShopLatitude, c.ShopLongitude));
如何从相关的最小距离取回相关的ShopID 查询和Linq声明?
答案 0 :(得分:1)
SELECT c.CouponID, c.ShopID, nearest.distance
FROM
Coupons C JOIN
(
SELECT CouponID, MIN (dbo.DistanceBetween (53.54613,9.98537,ShopLat,ShopLon)) as distance
FROM Coupons
GROUP BY CouponID
) nearest on c.CouponID = nearest.CouponID
AND dbo.DistanceBetween (53.54613,9.98537,ShopLat,ShopLon) = nearest.distance
ORDER BY CouponID, distance ASC
答案 1 :(得分:0)
只需修改您的SQL查询即可执行分组并加入您想要的地方。
创建一个表来保存距离,然后选择couponid和shopid匹配的最小值。