3

数据

ID-USER-ROLE-PERM
1   1   1   1
2   1   1   2
3   1   1   3
4   1   1   4
5   1   1   5
6   1   1   6
12  1   1   7
13  1   1   8
9   1   3   1
10  1   3   5
11  1   4   1
14  13  1   8

查询描述:有多少用户取值 1 为ROLE

结果应该是: 2

因为只有用户号 1 和 13 将值 1 作为ROLE

这是我返回 9 的错误查询:

SELECT COUNT(*) FROM assigned_roles WHERE ROLE = 1 GROUP BY ROLE

知道如何返回 2 吗?

4

1 回答 1

7

To count the number of different users use COUNT(DISTINCT USER).

Also you don't need GROUP BY ROLE as your WHERE clause ensures that there can only be a maximum of one group.

SELECT COUNT(DISTINCT USER) 
FROM assigned_roles 
WHERE ROLE = 1 

SQL Fiddle

于 2013-03-26T17:47:59.303 回答