473,748 Members | 2,353 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HowTo: Calculate business days - pure SQL approach.

FishVal
2,653 Recognized Expert Specialist
IMHO, the following is not a how-to-do instruction to solve a particular problem but more a concept-proof stuff demonstrating possibilities of SQL.

So, let us say the problem is to calculate business days count which is defined as count of days (optionally inclusive in the current implementation) excluding weekend days and holidays.

Let us say periods to calculate are stored in table associated with contacts.

[tblPeriods]
keyPeriodID - Autonumber(Long ), PK
keyContactID - Long, FK(tblContacts)
dteStart - Date/Time
dteEnd - Date/Time

The goal is to receive dataset containing sequential dates falling into date periods stored in the table with weekends and holidays excluded. Then, a simple grouping query will return desired results.


Step 1. Getting records.

To get all days falling into the periods we need to outer join [tblPeriods] with dataset containing all sequential dates.
Obviously using a table storing all dates is not a smart option. ;)
Better to generate it dynamically.
Obviously calendar dates are nothing more than all possible combinations of 1-31 days numbers, 1-12 month numbers and sensible range of year numbers. Certainly non-existing dates like 30-Dec and sometimes 29-Dec has to be omitted.
This gives an idea to use cartesian join of the following datasets:

[tblDays]
lngDay - Long, PK - natural numbers set 1-31

[tblMonts]
lngMonth - Long, PK - natural numbers set 1-12

[tblYears]
lngYear - Long, PK - natural numbers set ... :) ... let us say 2000 - 2014

The following query will combine these values into flat calendar 2000-2014, non existing dates are excluded using a feature of DateSerial() function to wrap day in a case of illegal argumnets.

Query: [qryFlatCalendar]
Expand|Select|Wrap|Line Numbers
  1. SELECT DateSerial(tblYears.lngYear,tblMonths.lngMonth,tblDays.lngDay) AS dteDate,
  2. tblYears.lngYear, tblMonths.lngMonth, tblDays.lngDay
  3. FROM tblYears, tblMonths, tblDays
  4. WHERE tblDays.lngDay=Day(DateSerial([tblYears].[lngYear],[tblMonths].[lngMonth],[tblDays].[lngDay]));
  5.  
Then, outer join with [tblPeriods]:

Query: [qryContactsPeri odsDays]
Expand|Select|Wrap|Line Numbers
  1. SELECT qryFlatCalendar.*, tblPeriods.keyPeriodID, tblPeriods.keyContactID, tblPeriods.dteStart, tblPeriods.dteEnd
  2. FROM qryFlatCalendar LEFT JOIN tblPeriods ON (tblPeriods.dteStart<=qryFlatCalendar.dteDate) AND (tblPeriods.dteEnd>=qryFlatCalendar.dteDate)
  3. WHERE Not tblPeriods.keyContactID Is Null;
  4.  
Pay attention to the ON clause of the query. In current implementation both sides of period are inclusive. If you consider other logic, then it is the place where it should be implemented.



Step 2. Excluding weekends and holidays.

Now we are going to exclude weekend days off and holidays.
And immediately appear two issues - as usual one is easy and other not so :)
  • Weekend days off depend on particular country.
  • Holidays sets depend on country too. The problem is that in some cases holiday date is the same in each year, in some cases it is calculated using some rules which not always could be easily embedded into relational database. So, for simplicity, let us store explicit full dates of that "irregular" holidays while "regular" holydays don't require more than a single record with Null year value.
Obviously days sets to exlude (weekends and holidays) when calculating business days should be associated with a particular country. As well as contacts.

This requires several tables:

[tblCountries]
keyCountryID - Autonumber(Long ), PK
txtCountry - Text

[tblCountryDaysO ff]
keyContactDayOf fID - Autonumber(Long ), PK
keyCountryID - Long, FK(tblCountries )
lngContactDayOf f - Long

[tblCountryHolid ays]
keyCountryHolid ayID - Autonumber(Long ), PK
keyCountryID - Long, FK(tblCountries )
txtHolidayName - Text

[tblContacts]
keyContactID - Autonumber(Long ), PK
keyCountryID - Long, FK(tblCountries )
txtContactName - Text

* the following table associates holidays with dates, if holiday occurs in definite day of month each year, then a single record is used with [lngYear]=Null, otherwise record for each year has to be created

[tblHolydayDates]
keyHolidayID - Autonumber(Long ), PK
lngDay- long
lngMonth - Long
lngYear - Long
keyCountryHolid ayID - Long, FK(tblCountryHo lidays)

Now two prejoins to get associations - Contact/DaysOff, Contact/HolidayDate

Query: [qryContactsDays Off]
Expand|Select|Wrap|Line Numbers
  1. SELECT tblContacts.*, tblCountryDaysOff.lngContactDayOff
  2. FROM tblContacts INNER JOIN tblCountryDaysOff
  3. ON tblContacts.keyCountryID = tblCountryDaysOff.keyCountryID;
  4.  
Query: [qryContactsHoli daysDates]
Expand|Select|Wrap|Line Numbers
  1. SELECT tblContacts.*, tblCountryHolidays.keyCountryHolidayID, 
  2. tblCountryHolidays.txtHolidayName, tblHolydayDates.keyHolidayID, tblHolydayDates.lngDay, tblHolydayDates.lngMonth, tblHolydayDates.lngYear
  3. FROM (tblContacts INNER JOIN tblCountryHolidays
  4. ON tblContacts.keyCountryID = tblCountryHolidays.keyCountryID)
  5. INNER JOIN tblHolydayDates
  6. ON tblCountryHolidays.keyCountryHolidayID=tblHolydayDates.keyCountryHolidayID;
  7.  
First we will exclude days off via the following outer join:

Query: [qryContactsPeri odsDaysWODaysOf f]
Expand|Select|Wrap|Line Numbers
  1. SELECT qryContactsPeriodsDays.*, qryContactsDaysOff.lngContactDayOff
  2. FROM qryContactsPeriodsDays
  3. LEFT JOIN qryContactsDaysOff
  4. ON 
  5. (qryContactsPeriodsDays.keyContactID=qryContactsDaysOff.keyContactID) AND (WeekDay(qryContactsPeriodsDays.dteDate)=qryContactsDaysOff.lngContactDayOff)
  6. WHERE qryContactsDaysOff.lngContactDayOff Is Null;
  7.  
Next we will exclude holidays:

Query: [qryContactsPeri odsBusinessDays]
Expand|Select|Wrap|Line Numbers
  1. SELECT qryContactsPeriodsDaysWODaysOff.keyPeriodID, 
  2. qryContactsPeriodsDaysWODaysOff.keyContactID, qryContactsPeriodsDaysWODaysOff.dteDate, 
  3. qryContactsHolidaysDates.txtHolidayName
  4. FROM qryContactsPeriodsDaysWODaysOff
  5. LEFT JOIN qryContactsHolidaysDates
  6. ON 
  7. (qryContactsPeriodsDaysWODaysOff.lngYear=qryContactsHolidaysDates.lngYear Or qryContactsHolidaysDates.lngYear Is Null)
  8. AND (qryContactsPeriodsDaysWODaysOff.lngMonth=qryContactsHolidaysDates.lngMonth) AND 
  9. (qryContactsPeriodsDaysWODaysOff.lngDay=qryContactsHolidaysDates.lngDay) AND 
  10. (qryContactsPeriodsDaysWODaysOff.keyContactID=qryContactsHolidaysDates.keyContactID)
  11. WHERE qryContactsHolidaysDates.keyCountryHolidayID Is Null;
  12.  


Step 3. Counting days.

Now dessert.

Query: [qryContactsPero idsBusinessDays Counts]
Expand|Select|Wrap|Line Numbers
  1. SELECT qryContactsPeriodsBusinessDays.keyPeriodID, 
  2. qryContactsPeriodsBusinessDays.keyContactID,
  3. Count(qryContactsPeriodsBusinessDays.dteDate) 
  4. AS CountOfdteDate
  5. FROM qryContactsPeriodsBusinessDays
  6. GROUP BY qryContactsPeriodsBusinessDays.keyPeriodID, 
  7. qryContactsPeriodsBusinessDays.keyContactID;
  8.  
Well. Almost done.
However periods having zero count of business days do not appear in the resulting list.

So, let Uroboros bite his tail.

Query: [qryFinalJoin]
Expand|Select|Wrap|Line Numbers
  1. SELECT tblPeriods.*, Nz(qryContactsPeroidsBusinessDaysCounts.CountOfdteDate,0) AS 
  2. lngBusinessDays
  3. FROM tblPeriods
  4. LEFT JOIN qryContactsPeroidsBusinessDaysCounts
  5. ON tblPeriods.keyPeriodID=qryContactsPeroidsBusinessDaysCounts.keyPeriodID;
  6.  
P.S. Holidays list in the attached database could be incomplete, wrong or irrelevant. I didn't try my best to make a good one. :D

P.P.S. Ok. No sample today because the maximum allowed size was 5k. :D Just another bug in current state of bytes.com.
Nov 27 '08 #1
5 24544
FishVal
2,653 Recognized Expert Specialist
Ok. Here is a sample.
Attached Files
File Type: zip Calendar.zip (42.3 KB, 718 views)
Nov 30 '08 #2
OldBirdman
675 Contributor
The sentence "Certainly non-existing dates like 30-Dec and sometimes 29-Dec has to be omitted." should replace Dec with Feb. Or maybe "Certainly the non-existing dates 31-Apr, 31-June, 31-Sep, 31-Nov, 31-Feb, 31-Feb and sometimes 29-Feb have to be omitted."
Dec 5 '08 #3
FishVal
2,653 Recognized Expert Specialist
Amen. :)

Thanks.
Dec 5 '08 #4
chevyas123
2 New Member
How do i write a function to calculate business days excluding weekends and holidays in oracle?
Actually i need to prepare a calendar for my monthly activities i.e activity x to be performed on 3rd workingday of month.
Can u please help me out with this as i am very new to oracle.
Plzzzzzzz
Jul 29 '09 #5
totomalas
31 New Member
thanks alot for this amazing work....I have had this problem for so long...I want to get all the records that are between... Todays Date and the first day of this year....

what i do now is this..

Between Date() and [ I let the user enter the 1st day of the year, e.g 1/1/2009]



I couldnt figure it out... please help..
Aug 2 '09 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
23826
by: Anthony Robinson | last post by:
Is anyone aware of a function (system or user defined) that will calculate business days? For instance: I have a column in as table called DATE. I want to be able to add five business days to that date and come up with a new date. Is that possible. Also, is there anyway that DB2 can be aware of holidays? Maybe load them onto the server in some type of reference file or something. I ask these questions because I'm working on a banking...
7
25993
by: Sam | last post by:
Hi, I use C# in my ASP.NET projects. Here's what I need to do: I want to add x business days to a given date i.e. add 12 business days to today's date. What is the best, fastest and most efficient way for me to do this? -- Thanks, Sam
8
7520
by: =?Utf-8?B?QWw=?= | last post by:
I am working in vb2005. how can I calculate business days (not including holidays and weekends) between 2 dates? thanks Al
1
2445
by: ArchMichael | last post by:
i need help again on calculating business days excluding holidays i have a field called assign date and i need to calculate 7 business days excluding holidays ( already have a table for holiday) from that date. i have read some forums on getting total business day but not the other way around
2
8708
by: rahulae | last post by:
help me with this I'm able to calculate total working days excluding weekends but how to exclude holidays,is there any other way apart from storing all the holidays in some table and not selecting those or else is there any other option
17
15421
by: trixxnixon | last post by:
i have a form with these fields Priority level: urgent critical standard business days: 1, 3, 15 date submitted: current date due date:
0
9226
debasisdas
by: debasisdas | last post by:
This function takes 2 dates as parameter and returns the number of working days. You need to add the list of holidays. (I have added a few as sample) CREATE OR REPLACE FUNCTION BUSINESS_DAYS ( i_Date1 IN DATE, i_Date2 IN DATE ) RETURN NUMBER IS
1
2788
by: chevyas123 | last post by:
How do i write a function to calculate business days excluding weekends and holidays in oracle? Actually i need to prepare a calendar for my monthly activities i.e activity x to be performed on 3rd workingday of month. Can u please help me out with this as i am very new to oracle. Plzzzzzzz
3
9945
by: PotatoChip | last post by:
I'm working in an Access XP database and I need to create a query which calculates what the date will be 6 business days after . I have no idea where to start and most posts I find on calculating business days pertains to subtracting data in two date fields. I can build an expression in my query to add the date, Date_Due: + 5 but that doens't address the business days. Thanks in advance!
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9552
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9326
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4877
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.