https://ps.tmpc.ru/ac78abbfae86

with data as (
                select distinct
                card_id,
                region_code,
                age_group_id,
                consul_need_id,
                consul_done_id,
                status_id,
                health_group_id,
                sport_group_id
                        from (
                    select
                        cd.region_kod as region_code,
                        floor(cd.age_group_id) as age_group_id,
                        cd.id as id_card_disp,
                        cd.status_id,
                        cc.health_group_id,
                        cc.sport_group_id,
                        hsa.consul_need_id,
                        hsa.consul_done_id,
                        cc.card_id
                        --row_number() over (partition by cd.patient_id, cd.type_id, cd.age_group_id order by cd.start_date desc) as rnt
                    from
                        link_diagnosis_after hsa,
                        card cd
                        join mz_register_sirots.card_conclusion cc on cc.card_id = cd.id
                             
                    where cd.type_id = 2
                    and status_id = 2
                    and cc.conc_date between to_date('01.01.2020','dd.mm.yyyy') and to_date('01.01.2021','dd.mm.yyyy')
                ) as result --where rnt = 1
          )
          select
                region_code, sum(case when age_group_id < 13 then 1 else 0 end) as "До года жизни",
              (sum(case when status_id = 2 then 1 else 0 end),0) as "Всего детей",
              (sum(case when health_group_id = 1 then 1 else 0 end),0) as "7.1",
              (sum(case when health_group_id = 2 then 1 else 0 end),0) as "8.1",
              (sum(case when health_group_id = 3 then 1 else 0 end),0) as "9.1",
              (sum(case when health_group_id = 4 then 1 else 0 end),0) as "10.1",
              (sum(case when health_group_id = 5 then 1 else 0 end),0) as "11.1",
              (sum(case when sport_group_id = 1 then 1 else 0 end),0) as "12.1",
              (sum(case when sport_group_id = 2 then 1 else 0 end),0) as "13.1",
              (sum(case when sport_group_id = 3 then 1 else 0 end),0) as "14.1",
              (sum(case when sport_group_id = 4 then 1 else 0 end),0) as "15.1",
              --(sum(case when consul_need_id in (1,2) then 1 else 0 end),0) "Сумма 18.1 и 19.1 + 19.1",
              (sum(case when consul_need_id = 3 then 1 else 0 end),0) as "18.1",
              --(sum(case when consul_done_id in (1,2) then 1 else 0 end),0) "18.1 + 19.1",
              (sum(case when consul_done_id = 3 then 1 else 0 end),0) as "19.1"
          from data
          group by region_code
,