You can use the SUM
but it has two points:
- Add up all columns
- Group for each yes/no/no
You could do it in one SELECT
, adding up the columns (sum(col1)+sum(col2)+...
), but would have the problem of individual values...
Then you could use a CASE WHEN
: (sum(CASE WHEN col1=1 THEN 1 ELSE 0 END)
) for each value and column...
That is an option:
select idConvenio,
(SUM(CASE WHEN EnderecoSi=0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoSit=0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoContr=0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoFis=0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN RazaoSi=0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN RazaoSit=0 THEN 1 ELSE 0 END)) TOT_0
,
(SUM(CASE WHEN EnderecoSi=1 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoSit=1 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoContr=1 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoFis=1 THEN 1 ELSE 0 END) +
SUM(CASE WHEN RazaoSi=1 THEN 1 ELSE 0 END) +
SUM(CASE WHEN RazaoSit=1 THEN 1 ELSE 0 END)) TOT_1
,
(SUM(CASE WHEN EnderecoSi=9 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoSit=9 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoContr=9 THEN 1 ELSE 0 END) +
SUM(CASE WHEN EnderecoFis=9 THEN 1 ELSE 0 END) +
SUM(CASE WHEN RazaoSi=9 THEN 1 ELSE 0 END) +
SUM(CASE WHEN RazaoSit=9 THEN 1 ELSE 0 END)) TOT_9
from exemplo
group by idConvenio
See here the fiddle working: http://sqlfiddle.com/#! 18/0283c/10
An observation of CASE WHEN: when it finds a value (0.1 or 9) returns 1, to sum an occurrence, but returns 0, ignoring.
I did the example with 6 columns just to speed up, but just add the others, assuming there are not many.
Another option would be to make two queries, one grouping only yes/no/without filling, put in a CTE and then group again and add.
Very good question Paul! + 1
– rbz