【问题标题】:How can I count the number of groups/field values for an ID?如何计算 ID 的组/字段值的数量?
【发布时间】: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


    【解决方案1】:

    输出 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
    

    【讨论】:

      【解决方案2】:

      对于每个输出,我将从以下内容开始 #:

      输出 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
      

      【讨论】:

        猜你喜欢
        • 2019-11-09
        • 1970-01-01
        • 2017-01-08
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 2021-11-16
        相关资源
        最近更新 更多