从日期使用年龄并创建年龄阶段列

时间:2018-03-03 05:55:31

标签: mysql sql

我有使用出生日期显示年龄阶段的问题,这里是我的查询和示例图像

SELECT 
res_fName,res_mName,
res_lName,rs.suffix,
rg.gender_Name,
TIMESTAMPDIFF(YEAR,res_Bday,CURDATE()) AS age,
(SELECT IF (TIMESTAMPDIFF(YEAR,res_Bday,CURDATE()) <=1,'INFANT','')) Age_Stage 
FROM resident_detail rd 
LEFT JOIN ref_suffixname rs ON rd.suffix_ID = rs.suffix_ID 
LEFT JOIN ref_gender rg ON rd.gender_ID = rg.gender_ID

SQL RESULT DISPLAY: SQL RESULT DISPLAY

年龄阶段

  • 孕产妇和新生儿( 0至1个月
  • 婴儿( 1至12个月
  • 幼儿( 13至24个月
  • 学龄前儿童( 2至4年
  • 学龄儿童( 5至8岁
  • Tweens( 9至12年
  • 少年( 13至19岁
  • 年轻人( 20至35岁
  • 中年人( 36至55岁
  • 高级( 56至100年

1 个答案:

答案 0 :(得分:2)

使用Case语句来确定Age Stage;

   SELECT res_fName,res_mName,res_lName,rs.suffix,rg.gender_Name,TIMESTAMPDIFF(YEAR,res_Bday,CURDATE()) AS age,
(case  
 when (TIMESTAMPDIFF(Month,res_Bday,CURDATE())<=1) then 'Maternal and Newborn'
 when (TIMESTAMPDIFF(Month,res_Bday,CURDATE())<=1 and TIMESTAMPDIFF(Month,res_Bday,CURDATE())<=12) then 'Babies'
when (TIMESTAMPDIFF(Month,res_Bday,CURDATE())<=13 and TIMESTAMPDIFF(Month,res_Bday,CURDATE())<=24) then 'Toddlers'
when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=2 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=4) then 'Preschoolers'
 when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=5 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=8) then 'School Age Children'
 when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=9 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=12) then 'Tweens '
when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=13 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=19) then 'Teenager'
when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=20 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=35) then 'Young Adult'
when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=36 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=55) then 'Middle-Aged Adults'
when (TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=56 and TIMESTAMPDIFF(Year,res_Bday,CURDATE())<=100) then 'Senior'
   end) Age_Stage 
FROM resident_detail rd LEFT JOIN ref_suffixname rs ON rd.suffix_ID = rs.suffix_ID LEFT JOIN ref_gender rg ON rd.gender_ID = rg.gender_ID