【发布时间】:2018-01-29 23:40:19
【问题描述】:
我有一张详细信息表,我想计算具有 2 个或更多不同 action_taken 值的 user_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:仅返回具有 >=2 个不同 action_taken 值的 user_id。
| user_id |
|---------|
| 1234 |
| 5566 |
这是我目前无法使用的:http://rextester.com/TUL87833。 HAVING 子句在详细信息中计算属于每个组的行数,不是 GROUP BY user_id, action_taken 子句指定的组数...
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 |
【问题讨论】:
标签: sql postgresql