1

Tengo una tabla en Mysql tipo:

Usuarios:
- usuario
- password
- email
- fecharegistro

Necesito hacer una consulta que me traiga todos los registros por año y por mes. He seguido un ejemplo en internet (porque no tengo ni idea de como hacerlo y de como funciona) y lo curioso es que me arroja los años y meses como los necesito, pero no me cuenta ningún registro. Me gustaría saber si me pueden ayudar indicándome en donde estoy comentiendo el error:

SELECT Y,m, COUNT(fecharegistro) AS registros
FROM (
  SELECT Y, m
  FROM
    (SELECT YEAR(CURDATE()) y UNION ALL SELECT YEAR(CURDATE())-1) years,
    (SELECT 1 m UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
      UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
      UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) months) ym
  LEFT JOIN usuarios
  ON ym.y = YEAR(FROM_UNIXTIME(fecharegistro))
     AND ym.m = MONTH(FROM_UNIXTIME(fecharegistro))
WHERE
  (y=YEAR(CURDATE()) AND m<=MONTH(CURDATE()))
  OR
  (y<YEAR(CURDATE()) AND m>MONTH(CURDATE()))
GROUP BY y, m

introducir la descripción de la imagen aquí

1
  • y en registros que debes mostrar?
    – user128299
    el 26 may. 2019 a las 18:44

1 respuesta 1

1

tu último where creo que esta de mas, ya que en el where de tu subconsulta ya hace la relación con mes y año de la fecha de registro

prueba quitando el el siguiente where

WHERE
  (y=YEAR(CURDATE()) AND m<=MONTH(CURDATE()))
  OR
  (y<YEAR(CURDATE()) AND m>MONTH(CURDATE()))

o puedes prueba con esta otra consulta

SELECT y,m,count(*) as registros FROM 
(SELECT YEAR(InvoiceDate) as y, MONTH(InvoiceDate) as m
  FROM Invoices 
  ) as t
GROUP BY y,m order by y desc,m desc
1
  • vaya, muchas gracias Juan Carlos, me sirvió de mucho. el 26 may. 2019 a las 20:10

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.