mysql - SQL:基于多对多表的条件的不同用户的计数

标签 mysql sql count many-to-many distinct

除了以下功能表之外,我还有一个典型的用户表

特点:

-----------------------
| userId |   feature  |
-----------------------
|   1    |   account  |
|   1    |  hardware  |
|   2    |   account  |
|   3    |   account  |
|   3    |  hardware  |
|   3    |    extra   |
-----------------------

基本上,我正在尝试获取一些用于报告目的的计数。特别是,我正在尝试查找拥有帐户和硬件的用户数量以及帐户总数。

我知道我可以执行以下操作来获取帐户总数

SELECT 
    COUNT(DISTINCT userId) as totalAccounts
FROM features
WHERE feature = "account";

但我不确定如何获取同时拥有帐户和硬件的用户数量。在此示例数据集中,我要查找的数字是 2。用户 1 和 3 都有帐户和硬件。

我更愿意在单个查询中执行此操作。可能使用 CASE(下面的 TotalAccounts 示例):

SELECT
    COUNT(DISTINCT(CASE WHEN feature = "account" THEN userId END)) as totalAccounts,
    COUNT( ? ) as accountsWithHardware
FROM features;

最佳答案

这是两个查询 - 一个用于所有用户计数,一个用于两种功能的用户计数 - 您可以将它们与交叉联接结合起来:

select 
  count_all_users.cnt as all_user_count, 
  count_users_having_both.cnt as two_features_user_count
from
(
  select count(distinct userid) as cnt
  from features
) count_all_users
cross join
(
  select count(*) as cnt
  from
  (
    select userid
    from features
    where feature in ('account', 'hardware')
    group by userid
    having count(*) = 2
  ) users_having_both
) count_users_having_both;

更新:经过一番思考,有一种更简单的方法。按用户分组,检测特征1和特征2是否存在。然后数数。

select
  count(*) as all_user_count,
  count(case when has_account = 1 and has_hardware = 1 then 1 end)
    as two_features_user_count
from
(
  select 
    userid,
    max(case when feature = 'account' then 1 else 0 end) as has_account,
    max(case when feature = 'hardware' then 1 else 0 end) as has_hardware
  from features
  group by userid
) users;

关于mysql - SQL:基于多对多表的条件的不同用户的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36559488/

相关文章:

c# - 通过 C# 中的参数在 SqlCommand 中的字符串列表

mysql - 查找引用表的连接数

sql - 解释不带组使用时的 COUNT 返回值

mysql - 分组依据、排序依据无法正常工作 - SQL 模式 - ONLY_FULL_GROUP_BY

mysql - 未知数量输入的数据库设计

php - 如何在 PHP 中显示之前简化 MySQL 错误?

c# - 如何使用可空的 setter/getter ?

php - Woocommerce WP - 从 post_type = shop_order | 获取 _sku 值SQL查询

c# - 如何在 C# 中使用 SMO 使用 FILE STREAM 备份和恢复数据库

php - 计算 laravel 中查询返回的行数