我正在使用连接查询来获取按标题分组的数据,其中标题存储在另一个用户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% |
----------------------------------
有点像这样的事情。我怎样才能做到这一点?
答案 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
子句。