这是我在SQLServer中的简化数据库布局:
表格书籍
BookID BookName
...... .........
表审核员:
ReviewerID ReviewerName
.......... ............
表评论
BookID ReviewerID ReviewDate Notes
...... .......... .......... .....
我需要找出最近评论过的3本“独特”书籍。例如,如果审核订单为book-a, book-b, book-c, book-c, book-d
,则输出应为book-d, book-c, and book-b
。
我尝试过的查询似乎都没有。获取书名的内部联接使其进一步复杂化。非常感谢您的指导。问候。
答案 0 :(得分:2)
这可以通过许多方法实现。
您可以尝试使用ROW_NUMBER函数,例如:
不确定这是100%正确,尝试提供sqlfiddles,将帮助其他人帮助您。
select TOP 3
*
from (
select
ROW_NUMBER() OVER (
PARTITION BY
BookID
ORDER BY
ReviewDate DESC
) reviewOrder,
*
from Reviews
) R
where
reviewOrder = 1
order by
ReviewDate DESC
答案 1 :(得分:1)
我在查询中编写了逻辑。我还给出了如何使用(即JOIN
)结果与其他表格。
;WITH CTE AS
(
SELECT *,
-- Get sequence number for all dates for each BOOKID in descending order
ROW_NUMBER() OVER(PARTITION BY BOOKID ORDER BY REVIEWDATE DESC)RNO
FROM [Table Reviews]
)
SELECT TOP 3 TB.BOOKNAME,TR.ReviewerName [LastReviewedBy],C.ReviewDate [LastReviewDate]
FROM CTE C
JOIN [Table Books] TB ON C.BOOKID=TB.BOOKID
JOIN [Table Reviewers] TR ON C.ReviewerID=TR.ReviewerID
WHERE RNO=1
ORDER BY DATEORDER DESC
<强> RESULT 强>