2

我有一个这样的 SQL 查询:

SELECT DISTINCT NewsID, UserID, PoliticianID
FROM Votes
WHERE UserID = 1010

结果如下所示:

NewsID | UserID | PoliticianID
40       1010     3
40       1010     10
38       1010     27
39       1010     27
40       1010     35

有没有办法27使用 SQL 从我上面的示例中获取数字?
我想得到PoliticianID用户投票最多的那个。

4

3 回答 3

2

试试这个:

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)
)

SQL 小提琴演示

或者:使用 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) ;

带有 CTE 的 SQL Fiddle 演示


更新

请注意:上面的解决方案将为您提供所有出现次数最多的 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;

更新的 SQL Fiddle

于 2012-12-10T11:27:08.290 回答
2

你可以试试这个

我创建了一个新的 TEMP 表,其中包含您的查询并根据需要为您提供结果。

SELECT TOP 1 PoliticianID, COUNT(PoliticianID) AS CNT
FROM 
    (SELECT DISTINCT NewsID, UserID, PoliticianID
     FROM Votes
     WHERE UserID = 1010) AS tempT
GROUP BY PoliticianID
ORDER BY CNT DESC
于 2012-12-10T11:35:58.847 回答
0

我想这应该工作......

SELECT TOP 1 NewsID, UserID, PoliticianID, COUNT(PoliticianID)
FROM Votes
WHERE UserID = 1010
GROUP BY NewsID, UserID, PoliticianID
ORDER BY COUNT(PoliticianID) DESC
于 2012-12-10T11:29:51.713 回答