分组和计数mysql

Posted

技术标签:

【中文标题】分组和计数mysql【英文标题】:Group by and count mysql 【发布时间】:2020-05-21 20:36:17 【问题描述】:

我需要计算每天有多少辆vehicleid,或者每天有多少辆,计算当天的车辆(“metrictimestamp”字段有日期)

【问题讨论】:

到目前为止你尝试了什么? 我只知道如何按某个字段分组,不知道如何统计该组内的其他字段 你快到了,你只需要将计数添加到 select 子句中,例如 select metrictimestamp, count(vehicleid)(你需要按 metrictimestamp 分组) 像这样:SELECT metrictimestamp,COUNT(vehicleid) FROM data? 是的,你需要group by metrictimestamp 【参考方案1】:

这看起来像一个直接聚合查询:

select date(metrictimestamp) metricdate, count(*) no_vehicles
from data
group by date(metrictimestamp)
order by metricdate

这假设 metrictimestamp 有一个时间组件 - 所以使用 date() 会删除它。

如果有vehicle_idnull 的行,请使用count(vehicle_id) 而不是count(*)。如果给定的vehicle_id 可能在某一天出现多次并且您只想计算一次,请使用count(distinct vehicle_id)

【讨论】:

以上是关于分组和计数mysql的主要内容,如果未能解决你的问题,请参考以下文章