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

时间:2016-04-11 21:22:27

标签: 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;

1 个答案:

答案 0 :(得分:0)

这两个查询 - 一个用于所有用户计数,一个用于双功能用户计数 - 您可以与交叉连接组合:

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;