Determining if a leap day falls between two days with DB2 SQL - sql

I have a table with two dates, "Start_Date" and "End_Date". In DB2 SQL, is there a way to determine if a leap day falls between these two dates?
Thank you!

Sure, you can do this using some date math and the DAYS function, by comparing the number of days between the the start and end date to the number of days between the start date and end date when they've both been shifted by 1 year.
If the number of days between the two dates is the same in both cases, then no leap day has occurred. If the number of days differs, then there has been at least 1 leap day.
This expression will return the number of leap days:
select
( DAYS(end_date + 1 year) - DAYS(start_date + 1 year) ) -
( DAYS(end_date) - DAYS(start_date) )
from
sysibm.sysdummy1
This should work as long as end_date >= start_date.
It's trivial to encapsulate this into a scalar User Defined Function.

Related

Get Number of Months and Days Between Dates

In PL/SQL I have 2 dates and I need to find out the number of months between them and the days as well. For example date 1 is 1/10/2022 and date 2 is 2/12/2022 that would be 1 month and 2 days. I'm pretty secure in obtaining the number of months, but the days number has been a thorn in my side. Sometimes it comes out correct, sometimes it comes out short and other times it comes out too far. I would imagine it is because of the different number of days in the months, but I can't prove that just yet. Any help is appreciated.
Oracle provides a months_between function to do the calculation.
That isn't a good idea as the number of days in a month varies, it's not exactly known what the decimal part of the number represents.
select months_between(date '2022-04-03', date '2022-01-01') from dual;
MONTHS_BETWEEN(DATE'2022-04-03',DATE'2022-01-01')
3.06451612903225806451612903225806451613
If you assume every month has 30 days, then comparisons over larger date ranges (years) will be out by more and more days the larger the difference gets.
However, if you combine methods, using months_between to get the months, and then assume 30 days for a month to get the days part from the remainder, it's more consistent over longer periods…
with dates as (select date '2022-01-01' as date_from, date '2022-04-03' as date_to from dual)
select months_between(date_to, date_from) ,trunc(months_between(date_to, date_from)) as months ,round(mod(months_between(date_to, date_from),1)*30) as days
from dates
MONTHS_BETWEEN(DATE_TO,DATE_FROM) MONTHS DAYS
3.06451612903225806451612903225806451613 3 2

Working days between two dates in Snowflake

Is there any ways to calculate working days between two dates in snowflake without creating calendar table, only using "datediff" function
After doing research work on snowflake datediff function, I have found the following conclusions.
DATEDIFF(DAY/WEEK, START_DATE, END_DATE) will calculate difference, but the last date will be considered as END_DATE -1.
DATEDIFF(WEEK, START_DATE, END_DATE) will count number of Sundays between two dates.
By summarizing these two points, I have implemented the logic below.
SELECT
( DATEDIFF(DAY, START_DATE, DATEADD(DAY, 1, END_DATE))
- DATEDIFF(WEEK, START_DATE, DATEADD(DAY, 1, END_DATE))*2
- (CASE WHEN DAYNAME(START_DATE) != 'Sun' THEN 1 ELSE 0 END)
+ (CASE WHEN DAYNAME(END_DATE) != 'Sat' THEN 1 ELSE 0 END)
) AS WORKING_DAYS
Here's an article with a calendar table solution that also includes a UDF to solve this in Snowflake (the business days are hard-coded, so that does require some maintenance, but you don't have to maintain a calendar table at least):
https://medium.com/dandy-engineering-blog/how-to-calculate-the-number-of-working-hours-between-two-timestamps-in-sql-b5696de66e51
The best way to count the number of Sundays between two dates is possibly as follows:
CREATE OR REPLACE FUNCTION SUNDAYS_BETWEEN(a DATE,b DATE)
RETURNS INTEGER
AS $$
FLOOR( (DAYOFWEEKISO(a) + DATEDIFF('days',a,b)) / 7 ,0)
$$
The above is better than using DATEDIFF(WEEK because the output of that function changes if the WEEK_START session parameter is altered away from the legacy default of 0
I have a way to calculate the number of business hours that elapse between a start time and end time but it only works if you make the following assumptions.
Asssume only 1 time zone for all timestamps
Any start or end times that occur outside of business hours should be rounded to nearest business hour time. (I.e. Assuming a schedule of 10:00am - 6:00 pm, timestamps occurring from midnight to 9:59am should be rounded to 10am, times after 6:00pm should be set to the next day at 10:00am)
Timestamps that occur on the weekends should be set to the opening time of the next business day. (In this case Monday at 10:00am)
My model does not account for any holidays.
If these 4 conditions are met then the following code should be enough for a rough estimate of business hours elapsed.
(DATEDIFF(seconds, start_time, end_time) --accounts for the pure number of seconds in between the two dates
- (DATEDIFF(DAY, start_time,end_time) * 16 * 60*60) --For every day between the two dates, we need to subtract out X number of hours. Where X is the number of hours not worked in a day. (i.e. for a standard 8 hour work day, set X =16. For a 10 hour day, set X = 14, etc.) We multiple by (60*60*16) to convert days into seconds.
- (DATEDIFF(WEEK, businness_hours_wait_time_start_at_est, businness_hours_first_touch_at_est)*(8*2*60*60)) --This accounts for the fact that weekends are not work days. Which is why we need to subtract an additional 8 hours for Saturday and Sunday.
)/(60*60*8) --We then divide by 60*60*8 to convert the business seconds into business days. We use 8 hours here instead of 24 hours since our "business day" is only 8 hours long.

How to get start & end of same week last year in DB2 using SQL?

I have a weekly report that uses these date parameters:
SELECT *
FROM TABLE
WHERE DATE_FIELD BETWEEN (CURRENT DATE - 8 DAYS) AND (CURRENT DATE - 2 DAYS)
This runs on Mondays to gather the previous week's data (Sun-Sat). What I want now is to run this for the same week of the previous year.
So for example, if the code above runs on Mon 29/06/20, it returns data from Sun 21/06/20 - Sat 27/06/20, i.e. week 26 of 2020. I want it to return data from Sun 23/06/19 - Sat 29/06/19, i.e. week 26 of 2019.
The report runs automatically so I can't just plug in the exact dates each time. I also can't just offset the date parameters to -357 and -367 days, as this gets thrown off by leap years.
I've searched for solutions but they all seem to rely on the DATEADD function, which my DB2 database doesn't recognise.
Does anyone know how I can get the result I'm looking for, please? Any advice would be appreciated! :)
The easiest way to do this is to build a calendar or dates table...(google sql calendar table)
Among the columns you'd have would be
date
year
month
quarter
dayofWeek
startOfWeek
endOfWeek
week_nbr
You can use the week() or week_iso() functions when loading the table, pay attention to the differences and pick the best fit for you.
Such a calendar table makes it easy to compare current period vs prior period.
If you assume that all years have 52 weeks, you can use date arithmetic:
SELECT *
FROM TABLE
WHERE DATE_FIELD BETWEEN (CURRENT DATE - (8 + 364) DAYS) AND (CURRENT DATE - (2 + 364) DAYS)
Because you want the week to start on a Monday, this doesn't have to take leap years into account. It is subtracting exactly 52 weeks -- and leap years do no affect weeks.
This gets more complicated if you have to deal with 52 or 53 week years.
A little bit complicated, but it should work. You may run it as is or test your own date.
SELECT
YEAR_1ST_WEEK_END + WEEKS_TO_ADD * 7 - 6 AS WEEK_START
, YEAR_1ST_WEEK_END + WEEKS_TO_ADD * 7 AS WEEK_END
FROM
(
SELECT
DATE((YEAR(D) - 1)||'-01-01')
+ (7 - DAYOFWEEK(DATE((YEAR(D) - 1)||'-01-01'))) AS YEAR_1ST_WEEK_END
, WEEK(D) - 2 AS WEEKS_TO_ADD
FROM (VALUES DATE('2020-06-29')) T(D)
);
The intermediate column YEAR_1ST_WEEK_END value is the 1-st Sat (end of week) of previous year for given date.
WEEKS_TO_ADD is a number of weeks to add to the YEAR_1ST_WEEK_END date.

How to subtract 13 weeks from a date in PL SQL?

I have a date in sql which will always fall on a Monday and I'm subtracting 13 weeks to get a weekly report. I am trying to get the same 13 week report but for last year's figures as well.
At the moment, I'm using the following:
calendar_date >= TRUNC(sysdate) - 91
which is working fine.
I need the same for last year.
However, when I split this into calendar weeks, there will also be a partially complete week as it will include 1 or 2 days from the previous week. I need only whole weeks.
e.g. the dates that will be returned for last year will be 14-Feb-2015 to 16-May-2015. I need it to start on the Monday and be 16-Feb-2015. This will change each week as I am only interested in complete weeks...
I would do this:
Get the date by substracting 91 days as you're already doing.
Get the number of the day of the week with TO_CHAR(DATE,'d')
Add the number of days until the next monday to the date.
Something like this:
SELECT TO_DATE(TO_DATE('16/05/2015','DD/MM/YYYY'),'DD/MM/YYYY')-91 + MOD(7 - TO_NUMBER(TO_CHAR(TO_DATE(TO_DATE('16/05/2015','DD/MM/YYYY'),'DD/MM/RRRR')-91,'d'))+1,7) d
FROM dual
next_day - returns date of first weekday named by char.
with dates as (select to_date('16/05/2015','DD/MM/YYYY') d from dual)
select
trunc(next_day( trunc(d-91) - interval '1' second,'MONDAY'))
from dates;
I want to get next monday from calculated date. In situation when calculated date is monday i have to move back to previous week ( -1 second).

How to get the difference between two dates (informix)?

How to get the difference between two dates (informix) in integer format like that
day = 15
mon = 2
year = 1
There are two sets of date/time values in Informix: DATE and DATETIME.
The DATE type is oldest (it was in the precursor to the SQL-based Informix), and represents the integer number of days since a reference date (where day 0 is 1899-12-31, so day 1 was 1900-01-01).
You get the difference between two DATE values in days by subtracting one from the other.
The DATETIME system is newer (but still old — circa 1990). You can take the difference between two DATETIME YEAR TO DAY values and get a result that is an INTERVAL DAY TO DAY (essentially the number of days).
You could also take the difference between two DATETIME YEAR TO MONTH values and get a result that is an INTERVAL YEAR TO MONTH.
However, there is no way to get a difference in years, months and days because there is no simple way to deduce that value. In fact, ISO SQL recognizes two classes of INTERVAL: those in the YEAR-MONTH group, and those in the DAY-SECOND group. You can't have an INTERVAL that crosses the MONTH/DAY barrier.
Use the MDY function :
select mdy(2,15,2014) - mdy(1,15,2014) from sysmaster:sysdual