mysql - Create statistic of table, use alias in case -
i have table holds birthdays , genders
select `tblresultdatetime`, `tblresultbirthdate`, `tblgendertexten` `ci_wizard_results` inner join ci_wizard_genders on ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid
so want create table points out age groups etc.
i believe first have convert dates ages:
select *,year(`tblresultdatetime`)-year(`tblresultbirthdate`) - (right(`tblresultdatetime`,5) < right(`tblresultbirthdate`,5)) age `ci_wizard_results`
but after that, not sure how continue. believe should use case:
select *,year(`tblresultdatetime`)-year(`tblresultbirthdate`) - (right(`tblresultdatetime`,5) < right(`tblresultbirthdate`,5)) age, count(case when age <= 30 , age> 39 1 end) agegroup3039 `ci_wizard_results`
but can't use alias in case, i'm kinda stuck. suggestion how continue?
(my final goal display data in report via reportico)
thanks!
assuming age calculate using
year(`tblresultdatetime`)-year(`tblresultbirthdate`)
you can use case when , group eg
select case when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 0 , 30 '0 - 30' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 31 , 40 '31 - 40' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 41 , 50 '41 - 50' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 51 , 60 '51 - 60' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 61 , 70 '61 - 70' else '70+' group end, sum(case when `tblgendertexten` = 'man' 1 else 0 end) man, sum(case when `tblgendertexten` = 'woman' 1 else 0 end) woman, sum(1) total `ci_wizard_results` inner join ci_wizard_genders on ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid group case when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 0 , 30 '0 - 30' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 31 , 40 '31 - 40' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 41 , 50 '41 - 50' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 51 , 60 '51 - 60' when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 61 , 70 '61 - 70' else '70+' group end union select 'total ', sum(case when `tblgendertexten` = 'man' 1 else 0 end) man, sum(case when `tblgendertexten` = 'woman' 1 else 0 end) woman, sum(1) total `ci_wizard_results` inner join ci_wizard_genders on ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid
Comments
Post a Comment