SQL:具有基于多对多条件的不同用户数 table
SQL: count of distinct users with conditions based on many to many table
我有一个典型的用户 table 除了以下特征 table
特点:
-----------------------
| 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;
我有一个典型的用户 table 除了以下特征 table
特点:
-----------------------
| 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;