在SQL中获取照片的排名

时间:2010-12-23 07:49:23

标签: sql-server

我有以下表格:

Photos [ PhotoID, CategoryID, ... ] PK [ PhotoID ]
Categories [ CategoryID, ... ] PK [ CategoryID ]
Votes [ PhotoID, UserID, ... ] PK [ PhotoID, UserID ]

照片属于一个类别。一个类别可能包含许多照片。用户可以对任何照片投票一次。照片可以由许多用户投票。

我想在照片所属的类别范围内选择照片的排名(通过计算它有多少票)。

SELECT * FROM Votes WHERE PhotoID = @PhotoID的计数是照片的投票数。我希望结果表生成整体排名列,并在类别中排名,以便我可以按顺序排序结果。

因此,例如,查询中的结果表应如下所示:

PhotoID    VoteCount      RankOverall     RankInCategory
1          48             1               7
3          45             2               5
19         33             3               1
2          17             4               3
7          9              5               5
...

...你明白了。我怎样才能做到这一点?到目前为止,我有以下查询来检索投票计数,但我也需要生成排名:

SELECT     PhotoID, UserID, CategoryID, DateUploaded,
                          (SELECT     COUNT(CommentID) AS Expr1
                            FROM          dbo.Comments
                            WHERE      (PhotoID = dbo.Photos.PhotoID)) AS CommentCount,
                          (SELECT     COUNT(PhotoID) AS Expr1
                            FROM          dbo.PhotoVotes
                            WHERE      (PhotoID = dbo.Photos.PhotoID)) AS VoteCount, Comments
FROM         dbo.Photos

1 个答案:

答案 0 :(得分:2)

查看(RANK (Transact-SQL)DENSE_RANK (Transact-SQL)

之类的内容
SELECT  p.PhotoID,
        ISNULL(v.CountVotes,0) CountVotes,
        RANK() OVER(ORDER BY ISNULL(v.CountVotes,0) DESC) RankInCategory,
        RANK() OVER(PARTITION BY p.CategoryID ORDER BY ISNULL(v.CountVotes,0) DESC) RankInCategory
FROM    Photos p LEFT JOIN 
        (
            SELECT  PhotoID,
                    COUNT(PhotoID) CountVotes
            FROM    Votes v 
            GROUP BY    PhotoID
        ) v ON  v.PhotoID = p.PhotoID