Doubt with select case

0

I have the following query:

select

f.no_equipe,
i.no_cbo,
count(b.tp_atend)


from

tb_equipe F,
tb_cds_prof G,
tb_cbo I,
tb_cds_ficha_atend_individual D,
tb_cds_atend_individual B

where

F.nu_ine = G.nu_ine and
G.nu_cbo_2002 = I.co_cbo_2002 and
D.co_cds_prof = G.co_seq_cds_prof and
B.co_cds_ficha_atend_individual = D.co_seq_cds_ficha_atend_indivdl

group by

F.no_equipe, I.no_cbo

I want to include two more fields:

  • count(where b.tp_atend = 1 ou 2)
  • count(where b.tp_atend = 3 ou 4)
  • I know I can do it using CASE, but I'm not sure how to create the command.

        
    asked by anonymous 18.12.2017 / 14:19

    1 answer

    1

    As you want to make a% conditional%, it is necessary to use COUNT and within it a SUM , if the condition is satisfied it will add 1 otherwise it will add 0.

    select
    
    f.no_equipe,
    i.no_cbo,
    count(b.tp_atend),
    sum(
        CASE
            WHEN b.tp_atend IN (1, 2) THEN 1
            ELSE 0
        END
    ) as count1,
    sum(
        CASE
            WHEN b.tp_atend IN (3, 4) THEN 1
            ELSE 0
        END
    ) as count2
    
    from
    
    tb_equipe F,
    tb_cds_prof G,
    tb_cbo I,
    tb_cds_ficha_atend_individual D,
    tb_cds_atend_individual B
    
    where
    
    F.nu_ine = G.nu_ine and
    G.nu_cbo_2002 = I.co_cbo_2002 and
    D.co_cds_prof = G.co_seq_cds_prof and
    B.co_cds_ficha_atend_individual = D.co_seq_cds_ficha_atend_indivdl
    
    group by
    
    F.no_equipe, I.no_cbo
    
        
    18.12.2017 / 14:23