Recuento separado para varios elementos dentro de un día MySQL

I am trying to display the status of multiple claims from one day at a time. For example, "date1" has 3 claims. Each claim has a different status. How can I display the status count for ALL claims within "date1". Namely, I would like to order my results by earliest to latest date then have three columns with a count for how many claims from that day have that status. The three status columns should add up to the total number of claims that day. This is what I would like it to look like: (St1 - St3 represent unique statuses)

Date      St1 St2 St3
12-02-12 | 1 | 2 | 3
12-03-12 | 2 | 5 | 3
12-04-12 | 7 | 3 | 8

The query I started working with looks like this, but it is entirely incorrect.

SELECT dates, statuses, COUNT(*) AS St1 FROM table_dates GROUP BY dates;

This was my attempt to get the count of only one status. Figured I had to start somewhere. Thank you.

preguntado el 29 de junio de 12 a las 20:06

2 Respuestas

You want to add status to your GROUP BY:

SELECT dates, status, COUNT(*) AS cnt
FROM table_dates
GROUP BY dates, status

This will give your results in a slightly different format from what you asked:

Date       | Status | cnt
2012-12-02 | 1      | 1 
2012-12-02 | 2      | 2 
2012-12-02 | 3      | 3 
2012-12-03 | 1      | 2 
2012-12-03 | 2      | 5 
2012-12-03 | 3      | 3 
2012-12-04 | 1      | 7 
2012-12-04 | 2      | 3 
2012-12-04 | 3      | 8 

This is probably a better format because if you later add new statuses neither your database schema, SQL query, nor client code will need to change.

Respondido el 29 de junio de 12 a las 20:06

Ok, I may be able to work with this. But is there any way to do this using separate columns for each status count instead? - shawn taylor

@user1251693: Yeah it's possible, but it's not really a very good idea. Presentation should be done in the client. - marca byers

Well this answered the question I was in the process of writing. - usumoio

Lo que puede hacer es algo como esto:

SELECT SUM(if(statuses = st1,1,0)) as st1, 
SUM(if(statuses = st2,1,0)) as st2, 
SUM(if(statuses = st3,1,0)) as st3 
    FROM table_dates 
    GROUP BY dates;

Respondido el 29 de junio de 12 a las 20:06

what do the 1,0 represent in the syntax? - shawn taylor

those are actual numbers - for each query - if the condition result is true - it will return the first value 1, and if false it will return the latter value 0. In this case you will summarize the number of rows where the status is st1 for instance - which is what you want. - Krakover

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.