试试这个:
SELECT *
FROM Votes
WHERE PoliticianID IN
(
SELECT PoliticianID
FROM votes
GROUP BY PoliticianID
HAVING COUNT(NewsID) = (SELECT MAX(NCount)
FROM
(
SELECT COUNT(*) NCount
FROM Votes
GROUP BY PoliticianID, UserId
) t)
)
或者:使用 CTE:
;WITH TheMostOccurredIds
AS
(
SELECT PoliticianID
FROM votes
GROUP BY PoliticianID
HAVING COUNT(NewsID) = (SELECT MAX(NCount)
FROM
(
SELECT COUNT(*) NCount
FROM Votes
GROUP BY PoliticianID, userID
) t)
)
SELECT *
FROM Votes
WHERE PoliticianID IN (SELECT PoliticianID FROM TheMostOccurredIds) ;
更新
请注意:上面的解决方案将为您提供所有出现次数最多的 Id,如果没有重复的最大值,这将正常工作。但是,如果您想获得 TOP 一个,如果有很多 id 具有相同的最大数量,就像您在评论中发布的示例一样,您可以使用这样的排名功能ROW_NUMBER() OVER(...)
:
;WITH VotesCountCTE
AS
(
SELECT [UserID], [PoliticianID], COUNT(*) votesCount
FROM votes
GROUP BY [UserID], [PoliticianID]
),TopVotes
AS
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY votescount) rownum
FROM VotesCountCTE
)
SELECT *
FROM TopVotes
WHERE rownum = 1;