Wednesday, June 25, 2008

Calculating Leap Year


I set up a table with approximately 200 years in it. Then using the formula from Wikipedia, I calculated whether it was a leap year or not.
If (
(Year Modulo 4 Is 0) And
(Year Modulo 100 Is Not 0)
)
Or (Year Modulo 400 Is 0)
Then Leap
Else No_Leap
To double-check, I set up the year with February, and asked what the last day of the month was. The subquery did all the work; the parent query asked for a count of distinct combinations.
Column Leap_or_No Heading 'Leap|or No'
Column Day Heading 'Feb|Last|Day' Format A4

Select Leap_or_No,
To_Char(FebDay,'dd') Day,
Count(*)
From (
Select Year,
-------------------------------------------
Case When (Mod(Year, 4)= 0
And Mod(Year, 100)<>0
)
Or Mod(Year, 400)= 0
Then 'Leap'
Else 'No Leap'
End
As
Leap_or_No,
--------------------------------------------
Last_Day(To_Date('01-Feb-'||Year))
As
FebDay
---------------------------------------------
From Year
)
Group By Leap_or_No,
To_Char(FebDay,'dd') ;
See Oracle documentation for further detail: Mod

No comments:

Post a Comment