Enumere los datos mysql agrupados y muestre num_rows para cada grupo

i have this SQL Code that select rows from a table and groups them together by the category column

echo '<strong>Categories</strong><br>';
    $sql="SELECT * from tickets where deleted = '' and DAY(datetime) = '04' and MONTH(datetime) = '".date("m")."' and YEAR(datetime) = '".date("Y")."' group by category order by datetime ASC ";
    $rs=mysql_query($sql,$conn);
    while($result=mysql_fetch_array($rs))
    {
        echo $result["category"].' ('.mysql_num_rows($rs).')<br>';
    }

when displaying the number of rows, its showing the same number on each one.

how can i make this display the correct number next to each 'category' ?

preguntado el 10 de septiembre de 13 a las 00:09

To use mysql_num_rows you'd have to do a separate select statement for each category because mysql_num_rows will always give you the total returned. You probably want to add a count field such as count(id) to give the number of rows for each given category. Try "SELECT count(id), * from tickets where deleted = '' and DAY(datetime) = '04' and MONTH(datetime) = '".date("m")."' and YEAR(datetime) = '".date("Y")."' group by category order by datetime ASC "; -

2 Respuestas

SELECT *, COUNT(category) AS my_groupcount from tickets

echo $result["category"].' ('.$result["my_groupcount"].')<br>';

Respondido el 10 de Septiembre de 13 a las 00:09

You probably want to do a query like this where you are using the COUNT function to tell you how many tickets are in each category grouping.

SELECT  category, COUNT(id) AS NumTickets, MIN(datetime) AS FirstDateTime
FROM tickets 
WHERE deleted = '' AND DAY(datetime) = 4 AND
        MONTH(datetime) = 12 AND YEAR(datetime) = '2012' 
GROUP BY category 
ORDER BY MIN(datetime)

Respondido el 10 de Septiembre de 13 a las 00:09

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