Search code examples
mysqlsqldatetimeunix-timestamp

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


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


Solution

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