2

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 3

3

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")
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

I tested it on MySQL 5.7, it works without FLOOR too. phpize.online/…
@SlavaRozhnev, that's great!!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.