[英]Oracle SQL: issue with age calculation
我需要按年齡將數據分為以下幾類:1-6,6-12,12-18,> 18。
我的問題是年齡計算為6時,該記錄未出現在任何類別中。 我希望按照我的邏輯,它應該在6-12之間。
為避免重復,我將查詢寫為: 1-6: age<=5
6-12: age >=6 <=11
12-18:age >=12 <=17
>18:age >=18
為什么我會丟失6歲的記錄?
編輯:這是我的年齡計算: (date1-DOB)/365.25 >= 6
(date1-DOB)/ 365.25 <= 11
我還嘗試將1-6設置為<6,將6-12設置為> 6 <12,將12-18設置為> 12 <18,但是在某些情況下,年齡在1-6和6-12的年齡均出現在6歲。 還有6-12和12-18中的12。 有辦法避免這種情況嗎?
您可以使用CASE
,在其中可以明確地寫出與每個范圍匹配的條件。 例如:
select x,
case
when x >= 1 and x < 6 then '1-6'
when x >= 6 and x < 12 then '6-12'
when x >= 12 and x < 18 then '12-18'
when x >= 18 then '>18'
else 'not matched'
end as range
from ( select level / 2 as x from dual connect by level < 20 )
您可以用不同的方式來做同一件事,但是我相信這是最易讀的內容之一。
您的..not覆蓋范圍始終在例如:
1-6: age <6 not <=5 and
6-12: age >=6 <=12 not age >=6 <=11
12-18:age >=12 <=18 not >=12 <=17
>18:age >=18
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.