select
code,
max(age) age_level,
max(age_interval) age_interval,
sum(total) total
from
(select
(case
when floor(months_between(sysdate, u.birth_date)/12) between 13 and 18 then 'Өсвөр үе'
when floor(months_between(sysdate, u.birth_date)/12) between 19 and 25 then 'Залуу үе'
when floor(months_between(sysdate, u.birth_date)/12) between 26 and 35 then 'Идэр үе'
when floor(months_between(sysdate, u.birth_date)/12) between 36 and 45 then 'Хижээл үе'
when floor(months_between(sysdate, u.birth_date)/12) between 46 and 60 then 'Өтөл үе'
when floor(months_between(sysdate, u.birth_date)/12) between 60 and 100 then 'Өндөр үе'
else 'other'
end) age,
(case
when floor(months_between(sysdate, u.birth_date)/12) between 13 and 18 then 'kid'
when floor(months_between(sysdate, u.birth_date)/12) between 19 and 25 then 'bigger_kid'
when floor(months_between(sysdate, u.birth_date)/12) between 26 and 35 then 'adult'
when floor(months_between(sysdate, u.birth_date)/12) between 36 and 45 then 'bigger_adult'
when floor(months_between(sysdate, u.birth_date)/12) between 46 and 60 then 'big_adult'
when floor(months_between(sysdate, u.birth_date)/12) between 60 and 100 then 'caption'
else 'other'
end) code,
(case
when floor(months_between(sysdate, u.birth_date)/12) between 13 and 18 then '13-18'
when floor(months_between(sysdate, u.birth_date)/12) between 19 and 25 then '19-25'
when floor(months_between(sysdate, u.birth_date)/12) between 26 and 35 then '26-35'
when floor(months_between(sysdate, u.birth_date)/12) between 36 and 45 then '36-45'
when floor(months_between(sysdate, u.birth_date)/12) between 46 and 60 then '46-60'
when floor(months_between(sysdate, u.birth_date)/12) between 60 and 100 then '60-100'
else 'other'
end) age_interval,
count(u.id) total
from sec_survey_users su
left join sec_users u on su.user_id = u.id
where su.survey_id = 'D3A21B1C2D8334C9E055824F7FFC5DF4' group by u.birth_date) mtable group by mtable.code;