我試圖在一個查詢中返回一組評分的平均值和計數。 在我發現瀏覽的例子之後,我在兩個查詢中很容易地管理它。例如:Spring Data JPA - 結果中有多個聚合函數的自定義查詢
@Query("SELECT AVG(rating) from UserVideoRating where videoId=:videoId")
public double findAverageByVideoId(@Param("videoId") long videoId);
但只要我想在同一個查詢中的平均數和計數,麻煩就開始了。經過許多小時的實驗,我發現這個工作,所以我在這裏分享。我希望它有幫助。
1)我需要的結果的新類:
的,我不得不引用的查詢類:
@Query("SELECT new org.magnum.mobilecloud.video.model.AggregateResults(AVG(rating) as rating, COUNT(rating) as TotalRatings) from UserVideoRating where videoId=:videoId")
public AggregateResults findAvgRatingByVideoId(@Param("videoId") long videoId);
一個查詢現在返回收視率的平均等級和數量
請確定您的自定義類 – Garry
公共類AggregateResults {私人最終雙評級; private final int totalRatings; public AggregateResults(double rating,long totalRatings){ this.rating = rating; this.totalRatings =(int)totalRatings; } public double getRating(){ return rating; } public int getTotalRatings(){ return totalRatings; } } – formica
謝謝...請將此添加到您的答案中,並與您的答案相關聯 – Garry