2017-08-21 12 views
0

私はの2つ以上の異なるaction_taken値を持つuser_idsをカウントしたいテーブルを持っています。IDのグループ/フィールド値の数をカウントするにはどうすればよいですか?

詳細:

| user_id | action_taken   | action_date | 
|---------|-----------------------|-------------| 
| 1234 | clicked on a link  | 1/1/2017 | 
| 1234 | went to the home page | 1/5/2017 | 
| 1234 | clicked on a link  | 1/7/2017 | 
| 1234 | clicked on a link  | 1/9/2017 | 
| 1234 | changed password  | 1/11/2017 | 
| 1234 | clicked on a link  | 1/13/2017 | 
| 9876 | went to the home page | 2/1/2017 | 
| 9876 | went to the home page | 2/5/2017 | 
| 9876 | went to the home page | 2/7/2017 | 
| 9876 | went to the home page | 2/9/2017 | 
| 5566 | clicked on a link  | 1/1/2017 | 
| 5566 | clicked on a link  | 1/5/2017 | 
| 5566 | changed password  | 1/7/2017 | 
| 5566 | clicked on a link  | 1/9/2017 | 
| 4433 | went to the home page | 1/5/2017 | 

所望の出力:

出力1:actions_takenの異なる値の数を返します。

| user_id | number_dift_action_taken_values | 
|---------|---------------------------------| 
| 1234 | 3        | 
| 4433 | 1        | 
| 5566 | 2        | 
| 9876 | 1        | 

出力2:action_takenの値が2つ以上異なるuser_idsのみを返します。

| user_id | 
|---------| 
| 1234 | 
| 5566 | 

これまでのところ、私がこれまで働いていないものは、http://rextester.com/TUL87833です。 HAVING句は、各グループに属する行詳細にの数、USER_ID、action_taken GROUP BY句で指定されたグループの数のない 数...

select 
    user_id 
    ,action_taken 
    ,count(*) 
from 
    tbl 
group by 
    user_id 
    ,action_taken 
having count(*) >=2; 

| user_id | action_taken   | count | 
|---------|-----------------------|-------| 
| 1234 | clicked on a link  | 4  | 
| 5566 | clicked on a link  | 3  | 
| 9876 | went to the home page | 4  | 

答えて

2

出力1カウントされます

SELECT user_id, 
     COUNT(DISTINCT action_taken) number_dift_action_taken_values 
    FROM t_tab 
GROUP BY user_id 

user_id number_dift_action_taken_values 
1234 3 
4433 1 
5566 2 
9876 1 

アウト結果私は、各出力#については、次のようなもので開始したい2

SELECT user_id 
    FROM t_tab 
GROUP BY user_id 
HAVING COUNT(DISTINCT action_taken) >= 2 

結果

user_id 
1234 
5566 
0

を置く:

出力1:

select 
user_id 
,count(distinct action_taken) as number_dift_action_taken_values 
into #Output1_tbl 
from details_tbl 
group by user_id 

出力2:

select * 
from #Output1_tbl 
where number_dift_action_taken_values >= 2 
+0

多分、having節を使って1つのクエリを出力することがあります。 –