【问题标题】:Count number of occurrences for each unique value [duplicate]计算每个唯一值的出现次数[重复]
【发布时间】:2012-10-25 12:25:11
【问题描述】:

基本上我有一个类似这样的表:

time.....activities.....length  
13:00........3.............1  
13:15........2.............2  
13:00........3.............2  
13:30........1.............1  
13:45........2.............3  
13:15........5.............1  
13:45........1.............3  
13:15........3.............1  
13:45........3.............2  
13:45........1.............1  
13:15........3.............3  

几点说明:

  • 活动可以在 1 到 5 之间
  • 长度可以在 1 到 3 之间

查询应该返回:

time........count  
13:00.........2  
13:15.........2  
13:30.........0  
13:45.........1  

基本上对于每个唯一时间,我都想计算活动值为 3 的行数。

那么我可以说:

At 13:00 there were X amount of activity 3s.
At 13:45 there were Y amount of activity 3s.

然后我想计算活动 1s、2s、4s 和 5s。所以我可以绘制每个独特时间的分布。

【问题讨论】:

    标签: sql count


    【解决方案1】:

    是的,你可以使用GROUP BY

    SELECT time,
           activities,
           COUNT(*)
    FROM table
    GROUP BY time, activities;
    

    【讨论】:

    • 谢谢!这似乎是最简单和最实用的解决方案:)
    • @JamesElder,乐于助人!您会考虑将答案标记为“已接受”吗? :-)
    • 我认为这个解决方案不会为 13:30 组显示值“0”
    【解决方案2】:
    select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
    from MyTable
    group by time
    

    SQL Fiddle Example

    输出:

    |  TIME | COUNT |
    -----------------
    | 13:00 |     2 |
    | 13:15 |     2 |
    | 13:30 |     0 |
    | 13:45 |     1 |
    

    如果你想统计一个查询中的所有活动,你可以这样做:

    select time, 
        coalesce(count(case when activities = 1 then 1 end), 0) as count1,
        coalesce(count(case when activities = 2 then 1 end), 0) as count2,
        coalesce(count(case when activities = 3 then 1 end), 0) as count3,
        coalesce(count(case when activities = 4 then 1 end), 0) as count4,
        coalesce(count(case when activities = 5 then 1 end), 0) as count5
    from MyTable
    group by time
    

    与按活动分组相比,这种方法的优势在于,即使该时间段没有该类型的活动,它也会返回计数 0。

    当然,这不会返回没有任何类型活动的时间段的行。如果需要,您需要使用左连接与列出所有可能的时间段的表。

    【讨论】:

    • 这非常有用,因为我想要在每个结果上计算不同值的结果。谢谢!
    • 带案例的计数是一个完美的解决方案
    【解决方案3】:

    如果我理解您的问题,这可行吗? (您必须用实际的列名和表名替换)

    SELECT time_col, COUNT(time_col) As Count
    FROM time_table
    GROUP BY time_col
    WHERE activity_col = 3
    

    【讨论】:

      【解决方案4】:

      您应该将查询更改为:

      SELECT time_col, COUNT(time_col) As Count
      FROM time_table
      WHERE activity_col = 3
      GROUP BY time_col
      

      这个 vl 工作正常。

      【讨论】:

        猜你喜欢
        • 2011-05-12
        • 2015-10-28
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        相关资源
        最近更新 更多