SQL查询以Unix TimeStamp格式的数据计算每月的行数

问题描述

在Mysql数据库中,我有一列存储Unix TimeStamp中的日期值(类型/ BigInt,毫秒)。我需要编写一个查询,使我能够计算每个月(与年份无关)的行数。

表格:

    +-------+----------------+
    |   id  |    Startdata   |
    +-------+----------------+
    |     1 |  1580841222491 |  
    |     2 |  1580841235885 |  
    |     3 |  1580841235872 |  
    |     4 |  1580843242865 |  
    |     5 |  1580841134857 | 
    |     6 |  1580841334855 | 
    |     7 |  1580842252695 | 
    |     8 |  1580844236845 | 
       ...         ... 
    +-------+----------------+

所需退货:

+-------+-------+
| count | month |
+-------+-------+
|     4 |     1 |  
|     1 |     2 |  
|     6 |     3 |  
|    51 |     4 |  
|    21 |     5 | 
|    29 |     6 | 
|    41 |     7 | 
|    18 |     8 | 
|    21 |     9 | 
|    11 |    10 | 
|    38 |    11 |
|    23 |    12 |
+-------+-------+

功能UNIX_TIMESTAMP不起作用

解决方法

from_unixtime也允许您指定输出的格式。就您而言,%m就是您所需要的。

select from_unixtime(Startdata/1000,"%m"),count(*)
from t
group by from_unixtime(Startdata/1000,"%m")
,

您可以尝试以下-

select month(date(from_unixtime(floor(Startdata/1000)))) as month_value,count(*) as cnt
from tablename
group by month(date(from_unixtime(floor(Startdata/1000))))

注意:如果您的MySql版本为8+,则不需要floor函数

,

表中的Startdata列以毫秒为单位,因此您需要将其除以1000才能转换为秒。因此查询将是:

SELECT 
    COUNT(*) AS `count`,MONTH(FROM_UNIXTIME(Startdata/1000)) AS `month`
FROM `mytable`
GROUP BY `month`;

实时示例here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...