You can use SUM
but you have two points:
- Add all columns
- Group for each yes / no / no fill
It would be possible to do in a single SELECT
, adding the columns ( sum(col1)+sum(col2)+...
), but would have the problem of the individual values ...
Then I could use a CASE WHEN
: ( sum(CASE WHEN col1=1 THEN 1 ELSE 0 END)
) for each value and each column ...
This 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 the fiddle here: link
An observation of CASE WHEN: When it finds a value (0,1 or 9) it returns 1, to add an occurrence, otherwise it returns 0, ignoring.
I've done the example with 6 columns just to speed up, but just add the others, assuming you do not have many.
Another option would be to make two queries, one grouping only yes / no / no fill, put in a CTE and then group again and add.