我有一个名为“users”的表,其中有很多用户,我的用户有 4 个不同的登录选项:passwd、facebook_login、google_login 和 aprofiel_login。 我想创建一个获取结果的查询:
- 用户总数
- 只设置了密码的用户
- 仅设置了 facebook_login 的用户
- 仅设置了 google_login 的用户
- 仅设置了 aprofiel_login 的用户
- 设置了以上 4 个选项中的 1 个以上的用户
我提出了以下查询,它给出了前 5 个,但我无法得到计算倍数的那个。
我的查询是这样的:
select count(*) total,
sum(case when passwd is not null and (facebook_login is null and google_login is null and aprofiel_login is null) then 1 else 0 end) gad,
sum(case when facebook_login is not null and (passwd is null and google_login is null and aprofiel_login is null) then 1 else 0 end) facebook,
sum(case when google_login is not null and (passwd is null and facebook_login is null and aprofiel_login is null) then 1 else 0 end) google,
sum(case when aprofiel_login is not null and (passwd is null and facebook_login is null and google_login is null) then 1 else 0 end) aprofiel
from `users`
where auth_level = 1
and is_account_active = 1
然后我考虑,我有我的总金额,我有所有其他单个用户的金额,如果我用所有其他用户减去总金额,我有多个登录用户的结果。 但是我如何在 MySQL 中执行此操作?
最佳答案
将此查询插入子查询,然后对派生列进行数学运算:
SELECT
t1.*,
total - (gad + facebook + google + aprofiel) as otherfield
FROM
(
select count(*) total,
sum(case when passwd is not null and (facebook_login is null and google_login is null and aprofiel_login is null) then 1 else 0 end) gad,
sum(case when facebook_login is not null and (passwd is null and google_login is null and aprofiel_login is null) then 1 else 0 end) facebook,
sum(case when google_login is not null and (passwd is null and facebook_login is null and aprofiel_login is null) then 1 else 0 end) google,
sum(case when aprofiel_login is not null and (passwd is null and facebook_login is null and google_login is null) then 1 else 0 end) aprofiel
from `users`
where auth_level = 1
and is_account_active = 1
) t1
关于mysql - 我如何使用 case 中的值在 mysql 中进行计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448774/