我是SQL Server,.NET和MVC 3/4的新手,所以请耐心等待。我在Linq-to-SQL中创建了一个返回所需数据的查询,但遗憾的是我的主机提供程序不支持DbGeography
类,特别是DbGeography.PointFromText
方法Description here。
所以我创建了一个存储过程,我得到了第一部分工作,但我很难总结和平均数据。我想返回SELECT
语句中Dish.DishId, Rest.RerstaurantId
语句分组的所有数据,rev.Rating
转换为AVG(rev.Rating)
,并为每个组添加计数列。
以下代码正在运行但不受支持:
public static DbGeography CreatePoint(double latitude, double longitude)
{
var text = string.Format(CultureInfo.InvariantCulture.NumberFormat,
"POINT({0} {1})", longitude, latitude);
return DbGeography.PointFromText(text, 4326);
}
public static double MilesToMeters(double? miles)
{
if (miles == null)
return 0;
return miles.Value * 1609.344;
}
[HttpGet]
public JsonResult TopRated(double lat, double lng, double miles)
{
var source = CreatePoint(lat,lng);
var dist = MilesToMeters(miles);
var reviews = (from r in db.Reviews
where r.Restaurant.Location.Distance(source) <= dist
group r by new {
r.Dish,
r.Restaurant.Name,
r.Restaurant.Lat,
r.Restaurant.Lng
} into rg
select new {
Rating = rg.Average(r => r.Rating),
Count = rg.Count(),
Dish = rg.Key.Dish,
Restaurant = new {
Name = rg.Key.Name,
Lat = rg.Key.Lat,
Lng = rg.Key.Lng
}
});
reviews = reviews.OrderByDescending(r => r.Rating);
return Json(reviews, JsonRequestBehavior.AllowGet);
}
以下是需要修改的存储过程
CREATE PROCEDURE [dbo].[SearchNearbyReview]
@Lat decimal(9,6),
@Lng decimal(9,6),
@Dist decimal(9,6)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @pos geography;
SET @pos = geography::STPointFromText('POINT('
+ CONVERT(varchar(15), @Lng) + ' '
+ CONVERT(varchar(15), @Lat) + ')',
4326)
SELECT
rev.Rating,
rest.RestaurantId,
rest.Name AS RestaurantName,
rest.[Address],
rest.City,
rest.[State],
rest.Zip,
rest.Lat,
rest.Lng,
dish.DishId,
dish.Name AS DishName
FROM dbo.Reviews rev
INNER JOIN dbo.Restaurants rest
ON rev.Restaurant_RestaurantId = rest.RestaurantId
INNER JOIN dbo.Dishes dish
ON rev.Dish_DishId = dish.DishId
WHERE rest.Location.STDistance(@pos) <= (@Dist * 1609.334)
ORDER BY rest.RestaurantId, dish.DishId
END
答案 0 :(得分:2)
select
t.AvgRating,
t.Count,
t.DishName,
t.DishId,
rest.RestaurantId,
rest.Name AS RestaurantName,
rest.[Address],
rest.City,
rest.[State],
rest.Zip,
rest.Lat,
rest.Lng
from dbo.Restaurants rest
join (select
avg(rev.Rating) as AvgRating,
count(1) as Count,
Restaurant_RestaurantId,
min(dish.Name) AS DishName,
DishId
from dbo.Dishes dish
join dbo.Reviews rev on rev.Dish_DishId = dish.DishId
group by Restaurant_RestaurantId, DishId
) as t
on t.Restaurant_RestaurantId = rest.RestaurantId
WHERE rest.Location.STDistance(@pos) <= (@Dist * 1609.334)
ORDER BY rest.RestaurantId, t.DishId