Oracle - 由不同的用户选择最多投票的项目

时间:2012-04-24 08:52:18

标签: sql oracle

我有如下的oracle表:

User - UserId,
Item - ItemId,
UserVote - UserVoteId, UserId, ItemId. 

现在用户可以多次投票。我对此查询很难:获得投票最多的项目唯一 - 意味着来自同一个人的多个投票仅计为一个。

如果它是SQL Server,我可能已经创建了临时表和所有,但我不知道如何在Oracle中处理。我也很难想到如何处理领带,这意味着如果两个项目都有18个“独特”投票。在这种情况下,我想要两件物品。

5 个答案:

答案 0 :(得分:3)

SELECT  *
FROM    (
        SELECT  q.*,
                DENSE_RANK() OVER (ORDER BY votes DESC) AS dr
        FROM    (
                SELECT  itemId, COUNT(DISTINCT userId) AS votes
                FROM    userVote
                GROUP BY
                        itemId
                ) q
        )
WHERE   dr = 1

答案 1 :(得分:1)

也许是这样的:

WITH CTE
AS
(
    SELECT
        COUNT(DISTINCT UserId) AS votes,
        item.ItemId
    FROM
        UserVote
    GROUP BY
        item.ItemId
)
SELECT
    *
FROM
    item
    LEFT JOIN CTE
        CTE.ItemId=item.ItemId
ORDER BY
    votes DESC;

这将COUNT投票不同的用户。因此,每个商品ID都有唯一的用户。我不知道你想要什么输出所以我订购了以便投票最多的项目是第一个。如果你只想要一个前十名或其他东西,你可以很容易地将它添加到选择。

答案 2 :(得分:1)

select ItemID,
       VoteCount
from
  (
    select ItemID,
           count(distinct UserId) as VoteCount,
           rank() over(order by count(distinct UserId) desc) as rn
    from UserVote
    group by ItemID
  ) U
where rn = 1;

答案 3 :(得分:0)

怎么样

SELECT "ItemId", COUNT(*) AS "VoteCount"
  FROM (SELECT DISTINCT "ItemId", "UserID"
          FROM "UserVote") a
  GROUP BY "ItemId"
  ORDER BY COUNT(*) DESC

分享并享受。

答案 4 :(得分:0)

以下ANSI查询返回投票最多的项目,不考虑同一用户的多次投票(您必须将返回的行限制在您的应用程序中):

SELECT ItemId, COUNT(DISTINCT UserId) AS "votes"
FROM UserVote
GROUP BY ItemId
ORDER BY "votes" DESC;

如果确实需要限制查询中的行数,可以使用Oracle SQL方言来实现:

SELECT ItemId, votes
FROM (
  SELECT ItemId, COUNT(DISTINCT UserId) AS "votes"
  FROM UserVote
  GROUP BY ItemId
  ORDER BY "votes" DESC
)
WHERE ROWNUM <= :n; -- :n is a placeholder for the number of rows to return