Mysql groups data by year and month

Desired effect:
 

plan:
 

① Use DATE _FORMAT( date , '%Y-%m-%d') function 

How to use DATE_FORMAT formatting depends on the subsequent format mode.

We just want to distinguish the year and month here, so we use %Y-%m in our sql:



SELECT  

DATE_FORMAT(create_time, '%Y-%m') AS DATE ,

COUNT(1)AS COUNT

FROM table

GROUP BY   DATE_FORMAT(create_time, '%Y-%m');

② Use left string interception

We intercepted the seventh position 2022-10, which is exactly 7th position:

SELECT  

LEFT(create_time,7) AS DATE,

COUNT(1)AS COUNT

FROM table

GROUP BY   LEFT(create_time,7);

Okay, that’s it.

Guess you like

Origin blog.csdn.net/qq_35387940/article/details/135223489