获得百分比和group by语句

时间:2015-10-02 13:05:21

标签: mysql sql select percentage

我正在使用连接查询来获取按标题分组的数据,其中标题存储在另一个用户ID为

的表中

所以查询就像是

SELECT title, COUNT(title) as cnt FROM users_titles
JOIN users
ON users_titles.uid = users.uid
WHERE users.useractivated = 1
GROUP BY title

现在我想添加一个额外的列,它将显示每种类型的百分比,如下所示:

----------------------------------
| title   |   cnt   | percentage |
----------------------------------
| 0       | 23658   | 23.67%     |
----------------------------------
| 1       | 53658   | 43.67%     |
----------------------------------
有点像这样的事情。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以将此查询与计算用户总数的查询交叉加入,并将这两个计数除以得到百分比:

SELECT     title, COUNT(title) AS cnt, COUNT(title) / total_count AS percentage
FROM       users_titles
JOIN       users ON users_titles.uid = users.uid
CROSS JOIN (SELECT COUNT(*) AS total_count 
            FROM   users) t 
WHERE      users.useractivated = 1
GROUP BY   title

注意:如果要将活动用户的数字表示为百分比,则还需要在内部查询中添加WHERE users.useractivated = 1子句。