SQL query to count the number of rows per month with data in Unix TimeStamp format

Viewed 387

In my Mysql database I have a column that stores the date values ​​in Unix TimeStamp (type / BigInt, milliseconds). I need to write a query that allows me to count the number of lines for each month (regardless of the year).

Table:

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

Desired return:

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

function UNIX_TIMESTAMP does not work

3 Answers

from_unixtime allows you to specify the format of the output as well. In your case, %m is all you need.

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

You can try the below -

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

Note: If your MySql version is 8+ then you don't need the floor function

The Startdata column in your table in milliseconds, so you need divide it by 1000 to convert into seconds. So query will be:

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

Live example here

Related