mysql - 我如何使用 case 中的值在 mysql 中进行计算?

标签 mysql

我有一个名为“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/

相关文章:

mysql - 使用 MSSQL 和 MySQL 数据库作为 Entity Framework 6 模型

javascript - 记录器.调试;输出 NULL 响应

java - 来自 Class.forName 的 ClassNotFoundException ("com.mysql.jdbc.Driver");

php - 无法使用准备好的语句从数据库中提取密码哈希

mysql - 通过 Linux 终端创建 MySQL 数据库并通过 phpMyAdmin 连接它

mysql - 使用 docker-compose.yml 文件的 docker 内部的 Mura CMS 数据库连接问题

MySQL 案例匹配所有条件

php - 我如何使用 jquery 从表中删除特定行

mysql - 在mysql中,设置连接mysql命令行的权限

php - Zend DB 如何管理数据库连接