如何在过去几天内选择最受好评的照片?

时间:2012-01-21 22:36:51

标签: asp.net sql sql-server sql-server-2008 tsql

这是我的数据背景:

Photos (ID, Title)
Users (ID, FullName)
Ratings (PhotoID, UserID, Value, Date)

业务规则:

  • 用户可以将照片评分为1到5
  • 给定用户只能对给定的照片评分一次

我希望在最后一天比如3天选择评分最高的照片。那么今天,昨天和前天哪张照片评分最高?如果可能的话,我想让天数变量。我必须显示最后N天,只有他们的评分不包括空日。

我想在单个查询/结果中获取照片,因为我想将它绑定到ListView以在Web表单上显示它们。

我是这样开始的:

DECLARE @days INT = 3

SELECT TOP (@days) ... FROM Ratings
INNER JOIN Photos ON Photos.ID = Ratings.PhotoID
GROUP BY DATEDIFF(day, [Date], CURRENT_TIMESTAMP)
ORDER BY DATEDIFF(day, [Date], CURRENT_TIMESTAMP) DESC

如何按PhotoID对组进行分组,按SUM(值)排序并从每组中选择第一个?非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

SELECT Date, TotalRating, Photos.*
FROM Photos
INNER JOIN 
(SELECT ROW_NUMBER() OVER (ORDER BY Date DESC) AS RowNumber, 
        PhotoID, Date, TotalRating
 FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Date, ORDER BY TotalRating DESC) AS inRowNumber,
              PhotoID, Date, TotalRating
        FROM (SELECT PhotoID, Date, SUM(Value) AS TotalRating
              FROM Photos
              GROUP BY PhotoID, Date
              HAVING SUM(Value) > 0 ) t)
 WHERE inRowNumber = 1) t ON Photos.Id = t.PhotoID
 WHERE RowNumber <= @days