これを試して:
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をすべて提供します。最大値が重複していない場合、これは正常に機能します。ただし、コメントに投稿した例のように、最大数が同じ ID が多数ある場合は、TOP を取得したい場合は、次のようなランキング関数を使用できます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;