sql實現根據身份證計算年齡


這種方式的思路是先判斷出生的月份和當前月份做對比,比當前月份小,則說明生日已過,直接年份相減就是周歲。

如果月份相等,則要判斷具體的日期,和當前的日期做對比,比當前日小,也說明生日已過,直接年份相減得周歲。

其他情況就是生日未過,年份相減之后還要減一,得周歲

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
;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM