Search code examples
mysqlsqldelphizeos

How to fix a count() in a query with a "group by" clause?


I have a function that gets a SQL code and inserts a count field in it and executes the query to return the number of rows in it. The objective is to have a dynamic SQL code and be able to get its record count no matter what code it has, because I use it in a registry filter window and I never know what code may be generated, because the user can add as many filters as he/she wants.

But as I use the group by clause, the result is wrong because it is counting the number of times a main registry appears because of the use on many join connections.

The result of that code above should only one row with a columns with 10 as result, but I get a new table with the first columns with a 2 in the first row and a 1 on the other rows.

If I take off the group by clause I will receive a 11 as a count result, but the first row will be counted twice.

What should I do to get a single row and the correct number?

SELECT 
 COUNT(*) QUERYRECORDCOUNT, // this line appears only in the Count() function 
 ARTISTA.*,
 CATEGORIA.NOME AS CATEGORIA,
 ATIVIDADE.NOME AS ATIVIDADE,
 LOCALIDADE.NOME AS CIDADE,
 MATRICULA.NUMERO AS MAP

FROM
 ARTISTA
 LEFT JOIN PERFIL ON PERFIL.REGISTRO = ARTISTA.ARTISTA_ID
 LEFT JOIN CATEGORIA ON CATEGORIA.CATEGORIA_ID = PERFIL.CATEGORIA
 LEFT JOIN ATIVIDADE ON ATIVIDADE.ATIVIDADE_ID = PERFIL.ATIVIDADE
 LEFT JOIN LOCALIDADE ON LOCALIDADE.LOCALIDADE_ID = ARTISTA.LOCAL_ATIV_CIDADE
 LEFT JOIN MATRICULA ON MATRICULA.REGISTRO = ARTISTA.ARTISTA_ID

WHERE 
 ((ARTISTA.SIT_PERFIL <> 'NORMAL') AND (ARTISTA.SIT_PERFIL <> 'PRIVADO'))
GROUP BY
 ARTISTA.ARTISTA_ID
ORDER BY 
 ARTISTA.ARTISTA_ID;

Solution

  • This always gives you the number of rows for any query you have:

    Select count(*) as rowcount from
    (
    
         Paste your query here
    
    ) as countquery