在子查询中选择最常出现的属性

时间:2012-12-10 11:20:27

标签: sql sql-server sql-server-2008

我有一个像这样的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

有没有办法从上面的例子中用SQL获取数字27? 我希望获得用户投票最多的PoliticianID

3 个答案:

答案 0 :(得分: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 Fiddle Demo

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

SQL Fiddle Demo With CTE


更新

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

Updated SQL Fiddle

答案 1 :(得分: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

答案 2 :(得分:0)

我想这应该有用......

SELECT TOP 1 NewsID, UserID, PoliticianID, COUNT(PoliticianID)
FROM Votes
WHERE UserID = 1010
GROUP BY NewsID, UserID, PoliticianID
ORDER BY COUNT(PoliticianID) DESC