cómo incluir una tercera columna en la tabla de resultados de un COUNT y agrupar por procedimiento

I have the following select statement which works fine

SELECT status_id, COUNT(status_id) As total
FROM tbl_project INNER JOIN lkp_status
ON tbl_project.status_id = lkp_status.record_id
GROUP BY status_id

I would like to include the status_name field in the result table but this is not allowed:

SELECT **status_name**, status_id, COUNT(status_id) As total
FROM tbl_project INNER JOIN lkp_status
ON tbl_project.status_id = lkp_status.record_id
GROUP BY status_id

"because it is not contained in either an aggregate function or the GROUP BY clause"

But I just want to have a third column indicating the name of the status_id for each count, which may not be unique :S

Gracias por cualquier sugerencia

preguntado el 30 de enero de 12 a las 19:01

You can't add STATUS_NAME to the GROUP BY? -

what table has the column status_name?, since in your examples you changed the tables from lkp_status a lkp_project_status -

Is your PK of status really called record_id? Porque no solo status_id? -

4 Respuestas

You need to ad status_name de las personas acusadas injustamente llamadas GROUP BY, otherwise it won't let you include it on your SELECT. Entonces, asumiendo que status_name pertenece a la lkp_status table, your query should be:

SELECT s.status_name, p.status_id, COUNT(status_id) As total
FROM tbl_project p
INNER JOIN lkp_status s
ON p.status_id = s.record_id
GROUP BY s.status_name, p.status_id

Respondido el 31 de enero de 12 a las 00:01

SELECT  tp.status_name,
        a.status_id,
        a.total

FROM (  SELECT status_id, COUNT(status_id) As total
        FROM tbl_project INNER JOIN lkp_project_status
        ON tbl_project.status_id = lkp_project_status.record_id
        GROUP BY status_id) A

INNER JOIN tbl_project tp
ON a.status_id = tp.status_id

Respondido el 31 de enero de 12 a las 00:01

SELECT  status_id,
        status_name = (SELECT status_name FROM tbl_project Where status_id = tp.status_id)
        COUNT(status_id) As total
  FROM  tbl_project tp INNER JOIN lkp_status ON tp.status_id = lkp_status.record_id
GROUP BY status_id

Respondido el 31 de enero de 12 a las 00:01

If your query actually works, you should be able to just add the name to both the SELECT clause and to the GROUP BY clause.

SELECT status_id, status_name, COUNT(status_id) As total
FROM tbl_project 
INNER JOIN lkp_status ON tbl_project.status_id = lkp_status.record_id
GROUP BY status_id, status_name

Este planteamiento de « podría give you surprising results if status names aren't unique.

Respondido el 31 de enero de 12 a las 00:01

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