2015-06-02 68 views
4

的最大值,我曾經在一個表得到一個列和id

MovieID以下幾列 - 點 - 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拉哈爾。我想出了以下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

您可以簡單地通過Order By和Limit來做到這一點。您通過MovieID訂購併且限制爲1將爲您提供電影的最多點信息。不要忘記根據自己的喜好和規模如何工作將其改爲上升或下降。

Select MovieID, Point Ordery By MovieID Limit 1 
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() 
}