Perform multiple operations on a single SQL code

0

I have a table in MySQL as follows and structure:

I would like to execute a SQL query that would do the following operations:

  • Total number of records ( total1 );
  • Count how many records have id_nps_answer between 0 and 6 ( total2 );
  • Count how many records have id_nps_answer between 9 and 10 ( total3 );
  • Perform the calculation ((total3 - total2) / total1) ;
  • The result would be made available to PHP.

    Is this possible? I'm not getting the code.

        
    asked by anonymous 03.11.2018 / 16:40

    2 answers

    3

    To bring everyone on the same line, you would have to nest the subselects, like this:

    SELECT 
        *, 
        (total3 - total2) / total1 as calculado
    FROM (
        SELECT COUNT(*) as total1 FROM nome_tabela) total1
        JOIN (SELECT COUNT(*) as total2 from nome_tabela WHERE id_nps_answer between 0 and 6) total2
        JOIN (SELECT COUNT(*) as total3 from nome_tabela where id_nps_answer between 9 and 10) total3
    
        
    03.11.2018 / 23:09
    2

    Good evening! Please let me know if the code I created worked after you tested. Thank you.

     -- 1 Totalizar o número de registros (total1);
     SELECT COUNT(id_nps_score) 
     FROM nome_da_tabela; 
    
     -- 2 Contar quantos registros possuem id_nps_answer entre 0 e 6 (total2);
     SELECT COUNT(id_nps_answer)
     FROM nome_da_tabela
     WHERE id_nps_answer BETWEEN 0 and 6;
    
     -- 3 Contar quantos registros possuem id_nps_answer entre 9 e 10 (total3);
     SELECT COUNT(id_nps_answer)
     FROM nome_da_tabela
     WHERE id_nps_answer BETWEEN 9 and 10;
    
     -- 4 Efetuar o cálculo ((total3 - total2) / total1);
     SELECT ((resultado3 - resultado2) / resultado1) AS '(total3-total2)/total1='
     FROM nome_da_tabela;
    
        
    03.11.2018 / 22:30