我有一个与Restaurent
加入的SQL Server表Product
:
SELECT
rm.RestaurantId, rm.RestaurantImage, rm.RestaurantName,
rm.RestaurantLocation,
pm.ProductName, rm.IsActive,
(6371 * acos(cos(radians(@userlat)) * cos(radians(RestaurantLatitude)) * cos(radians(RestaurantLongitude) - radians(@userlong)) + sin(radians(@userlat)) * sin(radians(RestaurantLatitude)))) AS distance
FROM
HomeMadeFood.dbo.RestaurentMaster AS rm
INNER JOIN
ProductMaster AS pm ON pm.RestaurentId = rm.RestaurantId
GROUP BY
rm.RestaurantId
ORDER BY
distance ASC
此查询返回如下输出:
RestID RestName Distance ProductName
-------------------------------------------------
1 A 16 Demo1
2 B 20 Demo2
1 A 16 Demo3
3 C 50 Demo4
我的预期输出应该是这样的
RestID RestName Distance ProductName
-------------------------------------------------
1 A 16 Demo1
2 B 20 Demo2
3 C 50 Demo4
如果我在group by
上使用RestId
,则会在第二列(图片)上引发错误
答案 0 :(得分:0)
以下内容通过将所有非聚合列移动到group by
子句来修复您看到的错误:
SELECT rm.RestaurantId, rm.RestaurantImage, rm.RestaurantName, rm.RestaurantLocation, pm.ProductName, rm.IsActive,
( 6371 * acos( cos( radians(@userlat) ) * cos( radians(RestaurantLatitude) ) * cos( radians(RestaurantLongitude) - radians(@userlong) ) + sin( radians(@userlat) ) * sin( radians(RestaurantLatitude) ) ) ) AS distance
from HomeMadeFood.dbo.RestaurentMaster rm inner join
ProductMaster pm
on pm.RestaurentId = rm.RestaurantId
group by rm.RestaurantId, rm.RestaurantImage, rm.RestaurantName, rm.RestaurantLocation, pm.ProductName, rm.IsActive,
rm.RestaurantLongitude, rm.RestaurantLatitude
order by distance asc;
您想要的结果要简单得多,所以我建议:
SELECT rm.RestaurantId, rm.RestaurantName, rm.IsActive,
( 6371 * acos( cos( radians(@userlat) ) * cos( radians(RestaurantLatitude) ) * cos( radians(RestaurantLongitude) - radians(@userlong) ) + sin( radians(@userlat) ) * sin( radians(RestaurantLatitude) ) ) ) AS distance
from HomeMadeFood.dbo.RestaurentMaster rm inner join
ProductMaster pm
on pm.RestaurentId = rm.RestaurantId
group by rm.RestaurantId, rm.RestaurantName, rm.IsActive,
rm.RestaurantLongitude, rm.RestaurantLatitude
order by distance asc;
答案 1 :(得分:0)
根据我的假设,你需要的是具有特定id的第一行,其中距离最小。 试试这个。
WITH MyNewTable AS(
SELECT rm.RestaurantId,rm.RestaurantImage,rm.RestaurantName,rm.RestaurantLocation,pm.ProductName,rm.IsActive,( 6371 * acos( cos( radians(@userlat) ) * cos( radians(RestaurantLatitude) ) * cos( radians(RestaurantLongitude) - radians(@userlong) ) + sin( radians(@userlat) ) * sin( radians(RestaurantLatitude) ) ) ) AS distance,
ROW_NUMBER() OVER(PARTITION BY pm.RestaurentId ) AS rk
FROM HomeMadeFood.dbo.RestaurentMaster AS rm
INNER JOIN ProductMaster AS pm
on pm.RestaurentId = rm.RestaurantId
ORDER BY distance ASC
)
SELECT
*
FROM
MyNewTable
WHERE rk = 1
如果它不起作用,请告诉我。