Skip to content
Advertisement

How to query MYSQL table to get counts of column occurrence overall and within past year?

I am using MySQL and want to create a query that will count how many times appointments happened per contact_id within the last year, last year, and how many times the occurrence happened overall.

My appointment table has the following rows with sample data:

So let’s say I want to see how many times contact_id ‘1’ had appointments, here how I’d want the result to look:

Is this query do-able with MYSQL?

I will be using it in an HTML/PHP/jQuery web application. I am going to have a button that will generate this information once clicked. Perhaps I should scrap the query idea and somehow manipulate it using some sort of jQuery table/data manipulation after a simple

SELECT * from appointments WHERE contact_id = 1'?

Advertisement

Answer

If you’d like to have it in a single query, you can try something like this:

=>

The above query will not return information for ‘No Show’. If you really need all statuses, you can do something like this:

=>

P.S. I do not like the years calculations I used in the query, however, keeping it as is here for simplicity. In real life, I’d use range comparison appointment_date BETWEEN CONCAT(YEAR(CURDATE()), '-01-01') AND CONCAT(YEAR(CURDATE()), '-12-31') instead of YEAR(appointment_date) = YEAR(CURDATE()).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement