Agregue COUNT (y calificador) a la declaración SQL

My database has 3 rows (not all columns listed):

**uFirst** | **uApp** 
  Dave     | approved
  John     | declined
  Jane     | no

This SQL is working, and displays all rows:

SELECT u.uID, u.uManT, u.uFirst AS 'NomFN', m.uFirst AS 'ManFN', u.uLast AS 'NomLN', m.uLast AS 'ManLN', u.uNomd, u.uApp, u.uApp, u.uAppd, u.uRep, u.uRepd, u.uManT, u.uStatus, u.uManR 
          FROM users AS u LEFT OUTER JOIN users AS m
          ON u.uManT = m.uID 
          WHERE u.uManR = " . $luID . " 
          AND u.uStatus = 'Physician' 
          ORDER BY u.uLast ASC";

When I try to add COUNT, it only displays 1 row (the approved one):

SELECT COUNT(CASE WHEN u.uApp = 'approved' THEN 1 END) AS Approved, 
       COUNT(CASE WHEN u.uApp = 'declined' THEN 1 END) AS Declined, 
       u.uID, u.uManT, u.uFirst AS 'NomFN', m.uFirst AS 'ManFN', u.uLast AS 'NomLN', m.uLast AS 'ManLN', u.uNomd, u.uApp, u.uApp, u.uAppd, u.uRep, u.uRepd, u.uManT, u.uStatus, u.uManR 
          FROM users AS u LEFT OUTER JOIN users AS m
          ON u.uManT = m.uID 
          WHERE u.uManR = " . $luID . " 
          AND u.uStatus = 'Physician' 
          ORDER BY u.uLast ASC";

I am trying to display all rows, and a count of the number of users approved. What am I doing wrong?

preguntado el 09 de marzo de 12 a las 14:03

Did you mean to use SUM? -

Share SHOW CREATE TABLE users -

1 Respuestas

In this case is just returning 1 row because you're not using GROUP BY, this query should get you what you want:

SELECT COUNT(uFirst) AS Total, u.uID, u.uManT, 
     u.uFirst AS 'NomFN', m.uFirst AS 'ManFN', u.uLast AS 'NomLN',
     m.uLast AS 'ManLN', u.uNomd, u.uApp, u.uApp, u.uAppd, u.uRep,
     u.uRepd, u.uManT, u.uStatus, u.uManR 
FROM users AS u 
LEFT OUTER JOIN users AS m ON u.uManT = m.uID 
WHERE u.uManR = " . $luID . " AND u.uStatus = 'Physician' 
GROUP BY uApp
ORDER BY u.uLast ASC";

respondido 09 mar '12, 14:03

This statement works, too. When would grouping on only 1 column be better than grouping on several like the suggestion above? - user1041931

It depends on what you want, basically counting and grouping by one filed like in this case counts the number of uFirst records for each uApp, the solution given by Michael Fredrickson counts all the records, since it groups by all the other fields (so both are valid solutions, but the result varies depending on what you'r expecting) - oscuroAjax

OK, I see thanks. However, still having a problem displaying the number of Approved (and your solution doesn't include my CASE: CASE WHEN u.uApp = 'approved' THEN 1 END). When I try to retrieve 'Approved', echo $row['Approved'];, I get 0. - user1041931

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