我有持有生日和性别的桌子
SELECT `tblresultdatetime`, `tblresultbirthdate`, `tblgendertexten`
FROM `ci_wizard_results`
INNER JOIN ci_wizard_genders ON ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid
所以我想创建一个指出年龄组等的表格。
我相信我首先必须将日期转换为年龄:
select *,year(`tblresultdatetime`)-year(`tblresultbirthdate`) - (right(`tblresultdatetime`,5) < right(`tblresultbirthdate`,5)) as age from `ci_wizard_results`
但在那之后,我不确定如何继续。我相信我应该使用案例:
select *,year(`tblresultdatetime`)-year(`tblresultbirthdate`) - (right(`tblresultdatetime`,5) < right(`tblresultbirthdate`,5)) as age,
count(case when age <= 30 and age> 39 then 1 end) as agegroup3039
from `ci_wizard_results`
但是你不能使用别名,所以我有点卡住了。有什么建议我可以继续吗?
(我的最终目标是通过reportico在报告中显示数据)
谢谢!
答案 0 :(得分:2)
假设只使用
计算年龄year(`tblresultdatetime`)-year(`tblresultbirthdate`)
你可以使用案例,例如
分组select
case when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 0 and 30 then '0 - 30'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 31 and 40 then '31 - 40'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 41 and 50 then '41 - 50'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 51 and 60 then '51 - 60'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 61 and 70 then '61 - 70'
else '70+' as Group end,
sum(case when `tblgendertexten` = 'man' then 1 else 0 end) as man,
sum(case when `tblgendertexten` = 'woman' then 1 else 0 end) as woman,
sum(1) as total
FROM `ci_wizard_results`
INNER JOIN ci_wizard_genders ON ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid
group by case when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 0 and 30 then '0 - 30'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 31 and 40 then '31 - 40'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 41 and 50 then '41 - 50'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 51 and 60 then '51 - 60'
when year(`tblresultdatetime`)-year(`tblresultbirthdate`) between 61 and 70 then '61 - 70'
else '70+' as Group end
union
select
'total ',
sum(case when `tblgendertexten` = 'man' then 1 else 0 end) as man,
sum(case when `tblgendertexten` = 'woman' then 1 else 0 end) as woman,
sum(1) as total
FROM `ci_wizard_results`
INNER JOIN ci_wizard_genders ON ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid