1

我有一张桌子,里面有生日和性别

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

谢谢!

4

1 回答 1

2

假设年龄是简单地使用

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
于 2016-11-05T20:58:32.147 回答