Count records per month in a MySQL table

1

I have a table in MySQL and would like to make the following query:

I need to know how many records I have according to the date. The field fecha I have it in the following format 2016-07-12 . How can I know the number of records per month for the current year?

For example:

Table usuario

  • id
  • nombre
  • dni
  • fecha
  • I have the query to count, but I do not know how to formulate the where for the aforementioned.

    select count(*) as cantidad_registros from usuario where ...
    
        
    asked by FeRcHo 05.01.2017 в 17:52
    source

    3 answers

    1

    If your fecha field does not include time, then you can use BETWEEN without problems.

    But just in case, I'll leave you with another option that works fine regardless of whether the fecha field includes a one hour portion or not. And it also has the advantage that you do not need to remember how many days you have the month, or to have to adjust the number of days depending on the year if the month you are interested in is February.

    select count(*)
      from usuario
     where fecha >= '2016-07-01'
       and fecha < '2016-08-01'
    

    Edit

    With the new clarifications, you can use the following query:

    select MonthName(fecha), count(*)
      from usuario
     where year(fecha) = year(curdate())
     group by MonthName(fecha)
    

    ... or, although it looks a bit more complicated, the following query is more optimal if you have an index defined in the fecha column and you have many records with different years. The optimization is due to the fact that I do not apply the function year to the column fecha , which allows the use of the index, if you have it:

    select MonthName(fecha), count(*)
      from usuario
     where fecha >= makedate(year(curdate()), 1)
       and fecha < makedate(year(curdate()) + 1, 1)
     group by MonthName(fecha)
    
        
    answered by 05.01.2017 / 18:01
    source
    3

    Just say it this way:

     SELECT count(*) FROM usuario WHERE (fecha BETWEEN '2016-07-01' AND '2016-07-31')
    

    Returns the number of results found with a date between July 1 to July 31 .

    If you want to show the account for each month try the following:

    SELECT MonthName(fecha) AS mes, count(*) AS numFilas FROM usuario GROUP BY mes
    
        
    answered by 05.01.2017 в 17:55
    1

    The query should look something like this

    select MonthName(fecha) as Month, count(*) as numRecords from usuario where MONTH(fecha) = 7 Group By Month 
    

    In the case of July, if you want it for all months you should remove the where

        
    answered by 05.01.2017 в 17:57