这是我的数据背景:
Photos (ID, Title)
Users (ID, FullName)
Ratings (PhotoID, UserID, Value, Date)
业务规则:
我希望在最后一天比如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(值)排序并从每组中选择第一个?非常感谢你的帮助。
答案 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