【问题标题】:SQL: count of distinct users with conditions based on many to many tableSQL:具有基于多对多表条件的不同用户计数
【发布时间】:2016-04-11 21:22:26
【问题描述】:

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

特点:

-----------------------
| 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;

【问题讨论】:

    标签: mysql sql count many-to-many distinct


    【解决方案1】:

    这是两个查询 - 一个用于所有用户计数,一个用于两个功能用户计数 - 您可以将其与交叉连接结合使用:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多