SQL Conditional Count

0

I have the following table

+----------+----------+
|   data   |    valor |
+----------+----------+
| 16/05/15 |        1 |
| 16/05/15 |        0 |
| 16/05/15 |        1 |
| 16/05/15 |        0 |
| 17/05/15 |        2 |
| 17/05/15 |        1 |
| 17/05/15 |        1 |
| 17/05/15 |        0 |
| 18/05/15 |        2 |
| 18/05/15 |        2 |
| 18/05/15 |        1 |
| 18/05/15 |        0 |
| 19/05/15 |        2 |
| 19/05/15 |        2 |
| 19/05/15 |        2 |
| 19/05/15 |        2 |
+----------+----------+

I need to make a sql that counts the amount of 0, 1 and 2, however I'm only able to do with sql, how can I make a single select?

SELECT data, COUNT(valor) 
FROM treatment_output 
WHERE valor = 0 
GROUP BY data ORDER BY data
    
asked by anonymous 20.01.2017 / 13:57

4 answers

4

You will need to select all records, group by value, and use the COUNT aggregation function.

As a result, COUNT will log each group.

SELECT 
    data,
    valor, 
    COUNT(valor) as quantidade
FROM treatment_output
GROUP BY data, valor ORDER BY valor

EDIT : Added field data in GROUP BY . The question does not clarify that you want grouping by date.

    
20.01.2017 / 14:12
3
SELECT data, COUNT(valor) 
FROM treatment_output 
--WHERE valor = 0 
GROUP BY data,valor ORDER BY data
    
20.01.2017 / 15:58
0

Look like this:

select count(*), valor from treatment_output
group by valor
    
20.01.2017 / 14:00
0
SELECT QTD,COUNT(*) Ocorrencias
From
(
SELECT data, COUNT(valor) QTD
FROM treatment_output 
WHERE valor = 0
GROUP BY data 
) VIRTUAL
Group by QTD
    
20.01.2017 / 17:11