2016-04-11 2 views
0

私は次の機能表に加えて、一般的なユーザーテーブルを持っているSQL:多くのテーブルに多くをもとに条件の異なるユーザーの数

機能:

----------------------- 
| 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はアカウントとハードウェアの両方を持っています。

私はこれを1回のクエリで行うことをお勧めします。おそらくCASE(以下totalAccountsための一例)を使用して:

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

答えて

0

これらは2つのクエリです - すべてのユーザー数、2-機能のユーザ数に1つに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; 
関連する問題