SQL count and sum

4

I have 6 SQL codes and all search the same table, it looks like this:

+-----+-----+-----+
|  A  |  B  |  C  |
+-----+-----+-----+
|  1  |  1  |  1  |
+-----+-----+-----+
|  2  |  1  |  5  |
+-----+-----+-----+
|  3  |  2  |  3  |
+-----+-----+-----+
|  4  |  1  |  1  |
+-----+-----+-----+
|  5  |  1  |  4  |
+-----+-----+-----+
|  6  |  1  |  5  |
+-----+-----+-----+
|  7  |  9  |  1  |
+-----+-----+-----+
|  8  |  3  |  1  |
+-----+-----+-----+

And the codes are these:

SELECT COUNT(*) as total, SUM(C) as soma FROM tabela WHERE B = 1;
SELECT COUNT(*) as total1 FROM tabela WHERE B = 1 AND C = 1;
SELECT COUNT(*) as total2 FROM tabela WHERE B = 1 AND C = 2;
SELECT COUNT(*) as total3 FROM tabela WHERE B = 1 AND C = 3;
SELECT COUNT(*) as total4 FROM tabela WHERE B = 1 AND C = 4;
SELECT COUNT(*) as total5 FROM tabela WHERE B = 1 AND C = 5;

The values returned are as follows:

total = 4
total1 = 2
total2 = 0
total3 = 0
total4 = 1
total5 = 2
soma = 16

Everything works perfectly, but would need everything to return in the same query, is it possible?

The intention is to count how many rows in the table, whose column B is equal to a value, then return in "total" and sum all the values in column C and return in "sum", but need to return it the number of times a value is repeated in the search.

    
asked by anonymous 27.06.2016 / 18:35

1 answer

6

What you need is something like this:

select 
count(*) total,
sum(c) soma,
sum(case when C = 1 THEN 1 ELSE 0 END) Tot1,
sum(case when C = 2 THEN 1 ELSE 0 END) Tot2,
sum(case when C = 3 THEN 1 ELSE 0 END) Tot3
from tabela
where B = 1

Projections in sum(case when CONDICAO THEN 1 ELSE 0 END) format are very useful for this type of scenario. In CONDICAO you must put something that evaluates to True or False. In this case, you are testing C = 1, 2 or 3, but you could put C IN (1,2,3) , even combining with logical operators, example C = 1 AND B = 2 . Therefore, if the record being evaluated returns True, add 1, otherwise add 0 (which makes no difference in the sum). Anyway, it's a way to count the records using SUM and not COUNT (*).

    
27.06.2016 / 18:58