這種方式的思路是先判斷出生的月份和當前月份做對比,比當前月份小,則說明生日已過,直接年份相減就是周歲。
如果月份相等,則要判斷具體的日期,和當前的日期做對比,比當前日小,也說明生日已過,直接年份相減得周歲。
其他情況就是生日未過,年份相減之后還要減一,得周歲
select
case when month(current_date) > substr(sfz,11,2) then year(current_date) - substr(sfz,7,4)
when month(current_date) = substr(sfz,11,2) and day(current_date) > substr(sfz,13,2) then year(current_date) - substr(sfz,7,4)
else year(current_date) - substr(sfz,7,4) - 1
end as age
from test_age
;