我有2张桌子。第一个名为“用户”的人看起来像这样:
id | Username
----------------------
1 | time
2 | bill
3 | jeff
第二个名为“帖子”的内容如下:
id | user | category
----------------------
1 | bill | 3
2 | tim | 1
3 | bill | 3
4 | bill | 2
“类别”列中的每个不同数字对应一个类别。
我正在尝试创建一个SQL查询,该查询将获得在特定类别中拥有超过10%帖子的所有用户。以下是我当前(不工作)代码对于类别3的看法:
SELECT
u.Username,
(
(SELECT COUNT(*) FROM posts WHERE user=u.Username AND category=3)
/ (SELECT COUNT(*) FROM posts WHERE user=u.Username)
* 100
) AS percentage
FROM users u
WHERE percentage > 10
此查询理论上应该返回'bill'。但是,它不起作用!我在某处有语法错误,或者我的方法是错误还是错误?
答案 0 :(得分:2)
您可以直接查询posts
表:
SELECT Username,
(SUM(Category = 3) / COUNT(*)) * 100 AS percentage
FROM posts
GROUP BY 1
HAVING percentage > 10
答案 1 :(得分:1)
在where子句中不能存在百分比别名。你必须使用having子句。
SELECT
u.Username,
(
(SELECT COUNT(*) FROM posts WHERE user=u.Username AND category=3)
/ (SELECT COUNT(*) FROM posts WHERE user=u.Username)
* 100
) AS percentage
FROM users u
HAVING percentage > 10