创建 table 的统计信息,以防万一

Create statistic of table, use alias in case

我有 table 保存生日和性别

SELECT `tblresultdatetime`, `tblresultbirthdate`, `tblgendertexten` 

FROM `ci_wizard_results`

INNER JOIN ci_wizard_genders ON ci_wizard_results.tblresultgender = ci_wizard_genders.tblgenderid

Returns:

现在我想像这样创建一个 table:


所以我想创建一个 table 来指出年龄组等。
我想我首先必须将日期转换为年龄:

    select *,year(`tblresultdatetime`)-year(`tblresultbirthdate`) - (right(`tblresultdatetime`,5) < right(`tblresultbirthdate`,5)) as age from `ci_wizard_results`


但是在那之后,我不知道如何继续。我相信我应该使用 case:

    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在报表中显示数据)

谢谢!

假设使用

简单地计算年龄
year(`tblresultdatetime`)-year(`tblresultbirthdate`)

您可以使用 case when 和 group by 例如

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