获取列和id的最大值

时间:2015-06-02 12:31:34

标签: sql linq

我在表格中有以下列

MovieID - Point - CategoryID

1-5-1

1-6-2

1-4-3

2-7-1 ...

正如您所看到的,每部电影都有多个类别。我想找到最高分的电影。但这一点必须是所有类别的平均值。以下linq查询找到了我想要的最大点,但我也需要movieID。

from tmp in
(from tmp in (
    (from Rating in db.Rating
    where
      Rating.DistrictID == 1
    group Rating by new {
      Rating.MovieID
    } into g
    select new {
      g.Key.MovieID,
      avg_point = (double?)g.Average(p => p.Point)
    }))
select new {
  tmp.avg_point,
  Dummy = "x"
})
group tmp by new { tmp.Dummy } into g
select new {
  max_point = (double?)g.Max(p => p.avg_point)
}

-------------------------------回答 感谢@Sari Rahal。我想出了以下linq查询:

(from tmp in (
    (from Rating in db.Rating
    where
      Rating.DistrictID == 1
    group Rating by new {
      Rating.MovieID
    } into g
    select new {
      g.Key.MovieID,
      avg_point = (double?)g.Average(p => p.Point)
    }))
orderby
  tmp.avg_point descending
select new {
  tmp.MovieID,
  tmp.avg_point
}).Take(1)

2 个答案:

答案 0 :(得分:2)

您的内部查询应该足够只需在平均值之后调用Max()

from Rating in db.Rating
where
  Rating.DistrictID == 1
group Rating by new {
  Rating.MovieID
} into g
select new {
  g.Key.MovieID,
  avg_point = (double?)g.Average(p => p.Point).Max()
}

答案 1 :(得分:2)

您可以通过Order By和Limit简单地完成此操作。您通过MovieID订购并限制为1将为您提供分数最多的电影的信息。不要忘记将其更改为升序或降序,具体取决于您的偏好以及您的规模如何运作。

Select MovieID, Point Ordery By MovieID Limit 1