我想在一个sql语句中执行两个计数。
SELECT COUNT(UserID) AS STAFF
FROM User_Role
WHERE(RoleID <> 1)
UNION
SELECT COUNT(UserID) AS STUDENTS
FROM User_Role AS User_Role_1
WHERE (RoleID = 1)
上面的代码有效但输出如下:
Staff
7
6
然而,我希望它也可以输出单独的颜色,如:
Staff Students
7 6
答案 0 :(得分:3)
只需使用条件聚合。
SELECT sum(case when roleid<>1 then 1 else 0 end) AS STAFF,
sum(case when roleid=1 then 1 else 0 end) AS STUDENTS
FROM User_Role
答案 1 :(得分:1)
在MySQL中,只需添加布尔表达式即可完成此操作:
SELECT SUM(RoleID <> 1) as STAFF, SUM(RoleID = 1) as Students
FROM User_Role;
这恰好是我喜欢的MySQL的扩展 - 许多语言将布尔值视为数字上下文中的整数。