How to make a Select with multiple SUM?

Asked

Viewed 193 times

2

Hello, I have a table of activities that lists activity data, including her status.

I would like to sum up the activities of a particular user and display in a graph, showing according to the status of the activity. (Type, always add +1 according to status).

For example:

The user Bruno has: 25 activities with expired status. 10 activities with pending status. 30 activities with completed status.

I’m trying to use the code below in Mysql:

SELECT  
  SUM(CASE WHEN STATUS = 'CONCLUIDO' THEN 1 ELSE 0) AS Concluido,
  SUM(CASE WHEN STATUS = 'CONCLUIDO_VENCIDO' THEN 1 ELSE 0) AS Concluido_Vencido,
  SUM(CASE WHEN STATUS = 'INICIADO' THEN 1 ELSE 0) AS Iniciado,
  SUM(CASE WHEN STATUS = 'INICIADO_VENCIDO' THEN 1 ELSE 0) AS Iniciado_Vencido,
  SUM(CASE WHEN STATUS = 'PENDENTE' THEN 1 ELSE 0) AS Pendente,
  SUM(CASE WHEN STATUS = 'VENCIDO' THEN 1 ELSE 0) AS Vencido
FROM tbl_atividades WHERE responsavel = "BRUNO";

  • The code is giving error.

Description of table tbl_activities:

inserir a descrição da imagem aqui

** Follows the error presented ** inserir a descrição da imagem aqui

Thank you!

  • 1

    Although you have not informed which error I believe that END is missing in each of the CASE. GROUP BY clause is not missing?

  • Ah, sorry. I’ll edit and show the error.

  • 1

    It would not be the case to use a Count with a group by status?

2 answers

2


The query is almost right, but lacked a detail to work properly, try this way it will certainly work.

SELECT  
  SUM(CASE WHEN STATUS = 'CONCLUIDO' THEN 1 ELSE 0 END) AS Concluido,
  SUM(CASE WHEN STATUS = 'CONCLUIDO_VENCIDO' THEN 1 ELSE 0 END) AS Concluido_Vencido,
  SUM(CASE WHEN STATUS = 'INICIADO' THEN 1 ELSE 0 END) AS Iniciado,
  SUM(CASE WHEN STATUS = 'INICIADO_VENCIDO' THEN 1 ELSE 0 END) AS Iniciado_Vencido,
  SUM(CASE WHEN STATUS = 'PENDENTE' THEN 1 ELSE 0 END) AS Pendente,
  SUM(CASE WHEN STATUS = 'VENCIDO' THEN 1 ELSE 0 END) AS Vencido
FROM tbl_atividades WHERE responsavel = "BRUNO";

1

What you are trying to do is count the number of activities per user. I imagine the following script solves your problem:

select status, count(*)
from tbl_atividades
where responsavel = 'BRUNO'
group by status;

This will show how many occurrences of each status exists for that particular user.

  • 1

    Right, Felipão. However I would like to do it that way right there. With the SUM. I appreciate your attempt with the COUNT.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.