是否可以做一个简单的查询来计算我在一个确定的时间段内有多少记录,比如一年,一个月,或者一天,有一个TIMESTAMP字段,比如:
SELECT COUNT(id)
FROM stats
WHERE record_date.YEAR = 2009
GROUP BY record_date.YEAR
甚至:
SELECT COUNT(id)
FROM stats
GROUP BY record_date.YEAR, record_date.MONTH
每月进行统计。
谢谢!
是否可以做一个简单的查询来计算我在一个确定的时间段内有多少记录,比如一年,一个月,或者一天,有一个TIMESTAMP字段,比如:
SELECT COUNT(id)
FROM stats
WHERE record_date.YEAR = 2009
GROUP BY record_date.YEAR
甚至:
SELECT COUNT(id)
FROM stats
GROUP BY record_date.YEAR, record_date.MONTH
每月进行统计。
谢谢!
当前回答
或者你可以像这样使用group by子句,
//to get data by month and year do this ->
SELECT FORMAT(TIMESTAMP_COLUMN, 'MMMM yy') AS Month, COUNT(ID) FROM TABLE_NAME GROUP BY FORMAT(TIMESTAMP_COLUMN, 'MMMM yy')
如果要按日期获取记录,则在组中按格式更改为 'dd-mm-yy'或'dd-MMMM-yyy'
其他回答
我希望每天都能得到类似的数据,经过一些试验,这是我在这个场景中能找到的最快的数据
SELECT COUNT(id)
FROM stats
GROUP BY record_date DIV 1000000;
如果你想每个月有一次,添加额外的零(00) 我不建议从“使代码可读”的角度考虑,它也可能在不同的版本中中断。但在我们的例子中,与我测试的其他更清晰的查询相比,这只花了不到一半的时间。
这是一个MySQL的答案(因为MySQL被标记在问题中),并在手册https://dev.mysql.com/doc/refman/8.0/en/date-and-time-type-conversion.html中有详细的说明
完整而简单的解决方案,具有类似的性能,但更短,更灵活的替代方案,目前活跃:
SELECT COUNT(*) FROM stats
-- GROUP BY YEAR(record_date), MONTH(record_date), DAYOFMONTH(record_date)
GROUP BY DATE_FORMAT(record_date, '%Y-%m-%d')
GROUP BY DATE_FORMAT(record_date, '%Y%m')
Note (primarily, to potential downvoters). Presently, this may not be as efficient as other suggestions. Still, I leave it as an alternative, and a one, too, that can serve in seeing how faster other solutions are. (For you can't really tell fast from slow until you see the difference.) Also, as time goes on, changes could be made to MySQL's engine with regard to optimisation so as to make this solution, at some (perhaps, not so distant) point in future, to become quite comparable in efficiency with most others.
或者你可以像这样使用group by子句,
//to get data by month and year do this ->
SELECT FORMAT(TIMESTAMP_COLUMN, 'MMMM yy') AS Month, COUNT(ID) FROM TABLE_NAME GROUP BY FORMAT(TIMESTAMP_COLUMN, 'MMMM yy')
如果要按日期获取记录,则在组中按格式更改为 'dd-mm-yy'或'dd-MMMM-yyy'
我试着使用上面的“WHERE”语句,我认为它是正确的,因为没有人纠正它,但我错了;经过一些搜索,我发现这是WHERE语句的正确公式,所以代码变成这样:
SELECT COUNT(id)
FROM stats
WHERE YEAR(record_date) = 2009
GROUP BY MONTH(record_date)