37

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

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。所以我可以绘制每个独特时间的分布。

4

4 回答 4

63

是的,您可以使用GROUP BY

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;
于 2012-11-05T16:19:35.073 回答
13
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time

SQL 小提琴示例

输出:

|  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。

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

于 2012-11-05T16:18:51.423 回答
5

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

SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3
于 2012-11-05T16:18:04.803 回答
0

您应该将查询更改为:

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

这个 vl 工作正常。

于 2017-03-09T05:39:06.627 回答