基本上我有一张类似的表:
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
几点说明:
查询应返回:
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。所以我可以绘制每个独特时间的分布。
答案 0 :(得分:55)
是的,您可以使用group by
:
select time, activities, count(*) from table group by time, activities;
答案 1 :(得分:8)
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time
<强>输出:强>
| 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。
当然,这不会返回没有任何类型活动的时间段的行。如果需要,您需要使用左连接和表,列出所有可能的时间段。
答案 2 :(得分:5)
如果我理解你的问题,这会有用吗? (您必须替换实际的列和表名称)
SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3
答案 3 :(得分:0)
您应该将查询更改为:
SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col
此vl正常工作。