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 に答える