How to round a date? Wait! What?


The ROUND function returns a number rounded to the decimal places specified by the function's parameter. If the function is called without a parameter, the number will be rounded to the nearest whole number.

ROUND(DATE, n)

select category, value
from (
select round( 0.4) "round( 0.4)" ,
       round(.5) "round(.5)",
       round(0.44, 1) "round(0.44, 1)",
       round(0.45, 1) "round(0.45, 1)",
       round(45.45,-1) "round(45.45,-1)",
       round(44.44, -1) "round(44.44, -1)"
from dual)
unpivot 
(value for category in(
 "round( 0.4)",
"round(.5)",
"round(0.44, 1)",
"round(0.45, 1)",
"round(45.45,-1)",
"round(44.44, -1)"
));
/


CATEGORY              VALUE
---------------- ----------
round( 0.4)               0
round(.5)                 1
round(0.44, 1)           .4
round(0.45, 1)           .5
round(45.45,-1)          50
round(44.44, -1)         40

6 rows selected. 

But did you know that the ROUND function can also be applied to the DATE data type?
The function returns a date rounded to the period specified as a parameter in the form of a date format. For example, if you specify "YEAR" as the parameter, the function will round the date either to the first day of the year (if the date is before July) or to the last day of the year (if the date is in July or later).
Check out the examples!

ROUND(date, fmt)

SELECT 
    category,
    value
FROM (
    SELECT
        ROUND(DATE '2024-12-19', 'W') AS round_week_dec_19,
        ROUND(DATE '2024-12-18', 'W') AS round_week_dec_18,
        ROUND(DATE '2024-02-15', 'Q') AS round_quarter_feb_15,
        ROUND(DATE '2024-02-16', 'Q') AS round_quarter_feb_16,
        ROUND(DATE '2024-07-01', 'YEAR') AS round_year_jul_01,
        ROUND(DATE '2024-06-30', 'YEAR') AS round_year_jun_30,
        ROUND(DATE '2024-06-16', 'MONTH') AS round_month_jun_16,
        ROUND(DATE '2024-06-15', 'MONTH') AS round_month_jun_15
    FROM dual
)
UNPIVOT (
    value FOR category IN (
        round_week_dec_19,
        round_week_dec_18,
        round_quarter_feb_15,
        round_quarter_feb_16,
        round_year_jul_01,
        round_year_jun_30,
        round_month_jun_16,
        round_month_jun_15
    )
);

CATEGORY             VALUE     
-------------------- ----------
ROUND_WEEK_DEC_19    2024-12-22
ROUND_WEEK_DEC_18    2024-12-15
ROUND_QUARTER_FEB_15 2024-01-01
ROUND_QUARTER_FEB_16 2024-04-01
ROUND_YEAR_JUL_01    2025-01-01
ROUND_YEAR_JUN_30    2024-01-01
ROUND_MONTH_JUN_16   2024-07-01
ROUND_MONTH_JUN_15   2024-06-01

8 rows selected. 

Have fun!

Komentarze