Query mysql return 4 Counts same table

Asked

Viewed 83 times

1

I would like to make a select in the same table that counts 4 different values, all with clauses, I’m trying this way but I’m not getting it, I want each Count to be done in a STATUS where I specify there, but it’s not returning me anything, where I’m going wrong?

SELECT count(id) as new AND status IN ('pgto_confirmado', 'pending'), count(id) as fup AND status IN ('processing'), count(id) as ce AND status IN('confirmar_entrega'), count(id) as complete AND status IN ('complete', 'repassado') 
FROM sgn_tbd_pedido 
WHERE data_entregar LIKE '%2018-03-08%' 
GROUP BY cidade;

I would like you to return for example:

Cidade  NEW  FUP  CE  COMPLETE
Campinas 19  11   5     100

2 answers

3

you can use CASE with aggregated functions. this is an example that can work in most DBMS:

select campo_id,
    count(*) total,
    sum(case when algumCampo = 'valoresperado' then 1 else 0 end) toal1,
    sum(case when algumCampo = 'outrovalor' then 1 else 0 end) toal12,
from suaTabela
group by cidade

There you can customize from the froma you find necessary, for more information see the SUM case

  • In this total Count(*), it will return me all the sums? in a single number?

  • In the case of Count(*) returns all records of the table the sum returns all that you epsecified through your predicate

1


The structure of CASE is a little different in the mysql; try the code below:

SELECT 
    sum (CASE status WHEN 'pgto_confirmado' THEN 1 WHEN 'pending' THEN 1 ELSE 0 END) as new
    sum (CASE status WHEN 'processing' THEN 1 ELSE 0 END) as fup,
    sum (CASE status WHEN 'confirmar_entrega' THEN 1 ELSE 0 END) as ce,
    sum (CASE status WHEN 'complete' THEN 1 WHEN 'repassado' THEN 1 ELSE 0 END) as complete
FROM sgn_tbd_pedido 
WHERE data_entregar LIKE '%2018-03-08%' 
GROUP BY cidade;
  • I tried and returned this ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') as new, count (CASE status WHEN 'processing' THEN 1 ELSE 0) as fup, count (CAS' at line 1)

  • will need to specify the as new or only new?

  • I added a END at the end of THEN 1 ELSE 0 and returned me ERROR 1630 (42000): FUNCTION db_op.count does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual

  • I made a change in response. I first switched the count for sum, was really wrong; I also added endto cases. Now it should work

  • 1

    This worked better for me, already has the cases mounted properly.

Browser other questions tagged

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