选择具有不同值的行的百分比

时间:2009-07-13 20:30:50

标签: sql mysql

在我运行的网站上,我让用户评价各个帖子(3,2,1)。我使用以下SQL(在MySQL中)来获得每个值的投票百分比:

SELECT vote, COUNT(*) * t.factor AS pct
FROM ratings
JOIN (
    SELECT 100 / COUNT(*) AS factor
    FROM ratings
) AS t
GROUP BY vote
LIMIT 0, 30;

这适用于计算整个表的行百分比。现在,我需要仅针对特定帖子的百分比,在表格中通过“id”列标识。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

假设投票列保存投票的价值,即(3,2,1),那么您需要以下查询来列出每次投票的百分比:

SELECT r.id, r.vote, SUM(r.vote)/t.totalVotes AS percentOfVotes
FROM ratings r
JOIN (SELECT id, COUNT(id) AS totalVotes
      FROM ratings
      GROUP BY id ) AS t ON t.id = r.id
WHERE r.id = @id -- id of post you want
GROUP BY r.id, r.vote

答案 1 :(得分:1)

这个问题似乎有点误导......但这就是我想象的那样。

SELECT vote, COUNT(*) * t.factor AS pct
FROM ratings
JOIN (
SELECT 100 / COUNT(*) AS factor
FROM ratings
where id = id of the post
) AS t
where id = id of the post
GROUP BY vote

答案 2 :(得分:1)

有一种方法可行,但我被告知并不是世界上最有效的方法如下:

SELECT vote, COUNT(*) * t.factor AS pct
FROM ratings
JOIN (
    SELECT 100 / COUNT(*) AS factor
    FROM ratings
    WHERE id = 36
) AS t
WHERE id = 36
GROUP BY vote
LIMIT 0, 30;

我曾尝试在内部和外部选择中添加where子句,但不是两者都添加!当然有道理。