sql database function (cut-off time on 4.30pm) - sql

I'm try to write SQL Database function. It should count number of working day with a cut-off point at 4.30pm. So any orders before 4.30pm appear in the total for the day before, and after 4.30pm in the total for that day. I found the code that count number of working day but I know how to add the cut-off point into the code?
create or replace
function "number_of_worked_day"
(p_start_dt date,
p_end_dt date
)
return number as
L_Number_Of_Days Number;
L_Start_Dt Date;
L_end_dt DATE;
Begin
L_Start_Dt :=Trunc(P_Start_Dt);
L_end_dt := trunc(p_end_dt);
SELECT COUNT(*)
into l_number_of_days
FROM (
WITH date_tab AS (SELECT TO_DATE (L_Start_Dt) + LEVEL - 1 business_date
FROM DUAL
CONNECT BY LEVEL <=
TO_DATE (L_end_dt)
- TO_DATE (L_Start_Dt)
+ 1)
SELECT business_date
FROM date_tab
WHERE TO_CHAR (business_date, 'DY') NOT IN ('SAT', 'SUN')
AND NOT EXISTS
( SELECT 1
FROM PUBLIC_HOLIDAY
WHERE business_date between START_DT and END_DT));
return l_number_of_days;
end;

I find your code a bit hard to follow. But the logic for handling a day starting at 4:30 p.m. is to subtract 16.5 hours from the time. For instance:
SELECT trunc(business_date - 16.5/24), count(*)
FROM date_tab
GROUP BY trunc(business_date - 16.5/24)
ORDER BY trunc(business_date - 16.5/24);

Related

get first day of a given week number in oracle

Please help to derive first day of a given week_no in oracle not from given date.
You can try following query:-
SELECT NEXT_DAY(MAX(d), 'SUN') REQUESTED_SUN
FROM (SELECT TO_DATE('01-01-2015', 'DD-MM-YYYY') + (ROWNUM-1) d FROM DUAL CONNECT BY LEVEL <= 366)
WHERE TO_CHAR(d, 'WW') = Your_Desired_WEEK_NO-1;
This might be helpful to you.
Use this query
Select TRUNC (Trunc(sysdate,'yyyy')+(:num-1)*7,'IW') from duaL;
:num is number of week from year 2015, or put year what you need instead of sysdate.
You can use this function to get the date of the ISO week:
CREATE FUNCTION TO_ISO_WEEK_DATE(
week NUMBER,
year NUMBER
) RETURN DATE DETERMINISTIC
IS
BEGIN
RETURN NEXT_DAY(
TO_DATE( TO_CHAR( year, '0000' ) || '0104', 'YYYYMMDD' )
- INTERVAL '7' DAY, 'MONDAY'
)
+ ( week - 1 ) * 7;
END TO_ISO_WEEK_DATE;
/

Oracle SQl Dev, how to calc num of weekdays between 2 dates

Does anyone know how can I calculate the number of weekdays between two date fields? I'm using oracle sql developer. I need to find the average of weekdays between multiple start and end dates. So I need to get the count of days for each record so I can average them out. Is this something that can be done as one line in the SELECT part of my query?
This answer is similar to Nicholas's, which isn't a surprise because you need a subquery with a CONNECT BY to spin out a list of dates. The dates can then be counted while checking for the day of the week. The difference here is that it shows how to get the weekday count value on each line of the results:
SELECT
FromDate,
ThruDate,
(SELECT COUNT(*)
FROM DUAL
WHERE TO_CHAR(FromDate + LEVEL - 1, 'DY') NOT IN ('SAT', 'SUN')
CONNECT BY LEVEL <= ThruDate - FromDate + 1
) AS Weekday_Count
FROM myTable
The count is inclusive, meaning it includes FromDate and ThruDate. This query assumes that your dates don't have a time component; if they do you'll need to TRUNC the date columns in the subquery.
You could do it the following way :
Lets say we want to know how many weekdays between start_date='01.08.2013' and end_date='04.08.2013' In this example start_date and end_date are string literals. If your start_date and end_date are of date datatype, the TO_DATE() function won't be needed:
select count(*) as num_of_weekdays
from ( select level as dnum
from dual
connect by (to_date(end_date, 'dd.mm.yyyy') -
to_date(start_date, 'dd.mm.yyyy') + 1) - level >= 0) s
where to_char(sysdate + dnum, 'DY',
'NLS_DATE_LANGUAGE=AMERICAN') not in ('SUN', 'SAT')
Result:
num_of_weekdays
--------------
2
Checkout my complete working function code and explanation at
https://sqljana.wordpress.com/2017/03/16/oracle-calculating-business-days-between-two-dates-in-oracle/
Once you have created the function just use the function as part of the SELECT statement and pass in the two date columns for Start and End dates like this:
SELECT Begin_Date, End_Date, fn_GetBusinessDaysInterval(Begin_Date, End_Date) AS BusinessDays FROM YOURTABLE;

Calling a function that return a table with dates

I have a problem with a function.
I need to get a table with dates of a month, name of the day and the amound of weekdays in that month.
I already found some help here and adapted it to my need, but I can't get the function running/compiled
Here is what I have so far:
create or replace TYPE DATE_ROW AS OBJECT
(
MyDate DATE,
Dayname VARCHAR2(12),
Amount Integer
)
create or replace TYPE DATE_TABLE as table of DATE_ROW
create or replace FUNCTION myfinaldays (mydate date)
RETURN DATE_TABLE
PIPELINED
IS
V_MYDATE DATE;
V_DAYNAME VARCHAR2(12);
V_AMOUNT NUMBER;
BEGIN
with this_month as (
select trunc(to_date('mydate'), 'mm')+level-1 dy
from dual
connect by level < (trunc(add_months(to_date('mydate'),1), 'mm')- trunc(to_date('mydate'), 'mm'))+1
)
FOR i IN 0 .. (select count(*) from this_month) LOOP
select (dy) Daydate,
to_char(dy, 'day'), Dayname,
( select count(*)
from this_month
where to_char(dy, 'dy') not in ('sat', 'sun')
) Amount
from this_month
where to_char(dy, 'dy') not in ('sat', 'sun')
and EXTRACT(day from to_date(dy)) = i;
pipe row (date_row(v_mydate,v_dayname, v_amount));
END LOOP;
RETURN;
END;
The function call would then be something like:
select * from date_table(cast(myfinaldays('01.02.12')));
I can only give one date as a parameter.
I hope someone can help me out here since this is slowly driving me mad.
Any ideas, examples, or thoughts would be greatly appreciated.
UPDATE:
Ok here is an update with mybe some more helpfull infos to my problem:
This is working and my aim is to put this in a function so I can call it with 1 parameter:
with this_month as (
select trunc(to_date('01.02.12'), 'mm')+level-1 dy
from dual
connect by level < (trunc(add_months(to_date('01.02.12'),1), 'mm')- trunc(to_date('01.02.12'), 'mm'))+1
)
select (dy) mydate, (select count(*) from this_month) Days_in_month
, to_char(dy, 'day') Dayname
, ( select count(*) from this_month where to_char(dy, 'dy') not in ('sat', 'sun') ) Amount
from this_month
where to_char(dy, 'dy') not in ('sat', 'sun') ;
for the loop I added: 'and EXTRACT(day from to_date(dy))=i' at the end.
I added a date so you can see what I need in the end. If I write mydate instead and enter 01.02.12 as parameter after running it in the developer it still works.
Errors I get compiling:
- Error(10,1): PL/SQL: SQL Statement ignored
- Error(15,5): PL/SQL: ORA-00928: Keyword SELECT missing
- Error(22,8): PLS-00113: END-Definer 'LOOP' must complete 'myfinaldays' in row 1, comlumn 10
- Error(23,4): PLS-00103: Found the symbol "RETURN"
The errors are translated since my Oracle does not run english so I hope to have guessed it correctly.
You have a number of problems here.
You can't use a select directly in for i in 1..x (and it should be 1, not 0), you'd have to select into a local variable and use that as the end value.
You can't use with as an input to a for loop; but you can use a cursor there, as I have below.
The select inside the loop with get no-data-found when i represents a Saturday or Sunday (the 4th in this case, assuming you're running it for February).
Getting the count of all non-weekend rows for every row is inefficient, though it doesn't really matter for such a small amount of data.
You are referring to to_date('mydate'); mydate is already a date, and 'mydate' is a string that has no relation to it.
And maybe some other things too, like assuming the date format and locale, since to_char(x, 'dy') will not return sat or sun everywhere, but I'll assume this is going to be used in a restricted way so you don't care about that too much.
From trying to figure out what output you're expecting, I think this will work (with modified types to get the days_in_month you added to the original question):
create or replace type date_row as object
(
mydate DATE,
dayname VARCHAR2(12),
days_in_month NUMBER,
amount NUMBER
)
/
create or replace type date_table as table of date_row
/
create or replace function myfinaldays (mydate date)
return date_table pipelined deterministic is
begin
for r in (
select *
from (
select dy as daydate,
to_char(dy, 'day') as dayname,
count(*) over () as days_in_month,
sum(case when to_char(dy, 'dy') in ('sat', 'sun')
then 0 else 1 end) over () as amount
from (
select trunc(mydate, 'mm')+level-1 dy
from dual
connect by level < (trunc(add_months(mydate, 1), 'mm')
- trunc(mydate, 'mm')) + 1
)
)
where to_char(daydate, 'dy') not in ('sat', 'sun')
) loop
pipe row (date_row(r.daydate, r.dayname, r.days_in_month, r.amount));
end loop;
end myfinaldays;
/
(If you don't want days_in_month then you can move the sat/sun check up and use the count for amount instead of the sum(case). The outer select is currently filtering on the day of the week so you can count all days, but that's not an issue if you don't want that value).
Then call as:
alter session set nls_date_format = 'DD.MM.RR';
select * from table(myfinaldays(to_date('01.02.12', 'DD.MM.RR')));
MYDATE DAYNAME DAYS_IN_MONTH AMOUNT
-------- ------------ ------------- ----------
01.02.12 wednesday 29 21
02.02.12 thursday 29 21
03.02.12 friday 29 21
06.02.12 monday 29 21
...
29.02.12 wednesday 29 21
21 rows selected.
Since your function is a table valued function (returns a table), you cannot call it as regular function.
you have join with it:
something like this in Oracle:
select * from date_table t
cross join table( myfinaldays(<t.date colum>))

How to populate calendar table in Oracle?

I want to maintain a calender table in Oracle DB which I want to populate with all the days of the year starting from 2011 to 2013 (it may be till any year). How can I do that?
Consider my DB table has columns and example dataset is:
S.No Cal_Dt DayName
1 01-01-2011 Monday
2 02-01-2011 Tuesday
3 03-01-2011 Wednesday
and so on.
I am more concerned with the Cal_Dt only here (DayName is optional).
This is a simple and easy way to do it
with calendar as (
select :startdate + rownum - 1 as day
from dual
connect by rownum < :enddate - :startdate
)
select rownum as "S.No", to_date(day,'dd_mm_yyyy') as "Cal_Dt", to_char(day,'day') as "DayName"
from calendar
with calendar as (
select rownum - 1 as daynum
from dual
connect by rownum < sysdate - to_date('1-jan-2010') + 1
)
select to_date('1-jan-2010') + daynum as monthdate
from calendar
;
declare
v_date date := to_date('20110101','yyyymmdd');
begin
while v_date < sysdate + 720 loop
insert into calender
values ( v_date, to_char(v_date,'DAY'));
v_date := v_date + 1;
end loop;
commit;
end;
/
This is not best practice and you should use Allesandro Rossi's solution. This may only be useful if you're using Oracle 9i or earlier and populating a large table.

Number of fridays between two dates

How do I find the number of fridays between two dates(including both the dates) using a select statement in oracle sql?
This will do it:
select ((next_day(date2-7,'FRI')-next_day(date-1,'FRI'))/7)+1 as num_fridays
from data
Perhaps best if I break that down. The NEXT_DAY function returns the next day that is a (Friday in this case) after the date.
So to find the first Friday after d1 would be:
next_day( d1, 'FRI')
But if d1 is a Friday that would return the following Friday, so we adjust:
next_day( d1-1, 'FRI')
Similarly to find the last Friday up to and including d2 we do:
next_day( d1-7, 'FRI')
Subtracting the 2 gives a number of days: 0 if they are the same date, 7 if they a re a week apart and so on:
next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')
Convert to weeks:
(next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')) / 7
Finally, if they are the same date we get 0, but really there is 1 Friday, and so on so we add one:
((next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')) / 7) + 1
I have to throw in my two cents for using a calendar table. (It's a compulsion.)
select count(*) as num_fridays
from calendar
where day_of_week = 'Fri'
and cal_date between '2011-01-01' and '2011-02-17';
num_fridays
-----------
6
Dead simple to understand. Takes advantage of indexes.
Maybe I should start a 12-step group. Calendar Table Anonymous.
See:
Why should I consider using an auxiliary calendar table?
The article's code is specifically for SQL Server but the techniques are portable to most SQL platforms.
With a Calendar table in place your query could be as simple as
SELECT COUNT(*) AS friday_tally
FROM YourTable AS T1
INNER JOIN Calendar AS C1
ON C1.dt BETWEEN T1.start_date AND T1.end_date
WHERE C1.day_name = 'Friday'; -- could be a numeric code
select sum(case when trim(to_char(to_date('2009-01-01','YYYY-MM-DD')+rownum,'Day')) = 'Friday' then 1 else 0 end) number_of_fridays
from dual
connect by level <= to_date('&end_date','YYYY-MM-DD') - to_date('&start_date','YYYY-MM-DD')+1;
Original source - http://forums.oracle.com/forums/thread.jspa?messageID=3987357&tstart=0
Try modifying this one:
CREATE OR REPLACE FUNCTION F_WORKINGS_DAYS
(V_START_DATE IN DATE, V_END_DATE IN DATE)
RETURN NUMBER IS
DAY_COUNT NUMBER := 0;
CURR_DATE DATE;
BEGIN -- loop through and update
CURR_DATE := V_START_DATE;
WHILE CURR_DATE <= V_END_DATE
LOOP
IF TO_CHAR(CURR_DATE,'DY') NOT IN ('SAT','SUN') -- Change this bit to ignore all but Fridays
THEN DAY_COUNT := DAY_COUNT + 1;
END IF;
CURR_DATE := CURR_DATE + 1;
END LOOP;
RETURN DAY_COUNT;
END F_WORKINGS_DAYS;
/
SELECT (NEXT_DAY('31-MAY-2012','SUN')
-NEXT_DAY('04-MAR-2012','SUN'))/7 FROM DUAL
select ((DATEDIFF(dd,#a,#b)) + DATEPART(dw,(#a-6)))/7