1

我有如下的 oracle 表:

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

现在用户可以多次投票。我很难处理这个查询:Get item(s) most voted uniquely - 这意味着来自同一个人的多张选票仅计为一张。

如果是 SQL Server,我可能已经创建了临时表和所有,但我不知道如何在 Oracle 中处理。我也很难考虑如何处理平局,这意味着如果两个项目都有 18 个“唯一”选票。在那种情况下,我想要这两个项目。

4

5 回答 5

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
于 2012-04-24T08:59:55.380 回答
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 的唯一用户。我不知道你想要什么输出,所以我订购了得票最多的项目。如果您只想要前 10 名或其他内容,您可以很容易地将其添加到选择中。

于 2012-04-24T08:58:06.947 回答
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;
于 2012-04-24T09:09:18.263 回答
0

怎么样

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

分享和享受。

于 2012-04-24T11:36:45.083 回答
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
于 2012-04-24T13:40:01.347 回答