Pregunta

I have two tables, prisoner and person.

Prisoner:
prisoner_id
person_ssn
sentence_start 
sentence_end

Person
first_name
last_name
person_ssn

If the sentence_start field is of type DATE, is it possible for me to calculate which month has had the most prisoners added and then show that month and how many there were?

¿Fue útil?

Solución

You simple need to run a COUNT query and GROUP the results by month and possibly year:

SELECT   YEAR(sentence_start) AS Y, MONTH(sentence_start) AS M, COUNT(*) AS C
FROM prisoner
GROUP BY YEAR(sentence_start), MONTH(sentence_start)

It is also possible to use the MySQL EXTRACT function to obtain same results MUCH faster:

SELECT   EXTRACT(YEAR_MONTH FROM sentence_start) AS YM, COUNT(*) AS C
FROM prisoner
GROUP BY EXTRACT(YEAR_MONTH FROM sentence_start)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top