1

我有一个包含这些示例行的表:

优惠券ID 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 的最小距离:

优惠券ID距离
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));

我怎样才能从查询和 Linq 语句中获取最小距离的相关 ShopID?

4

2 回答 2

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 
于 2013-03-27T17:34:41.900 回答
0

只需修改您的 sql 查询以执行您想要的分组和加入。

创建一个表格来保存距离,然后选择 couponid 和 shopid 匹配的最小值。

于 2013-03-27T16:58:00.377 回答