generate date range per year basis - oracle

I want to generate date range between trunc('7/1/2014','mm/dd/yyyy') and trunc(sysdate-1)+0.99999 (from 7/1/2014 till yesterday midnight) per year basis.
please refer to the attached image for expected result (https://i.stack.imgur.com/UD4Ub.png)

Something like this. Adapt as needed. You probably won't select * from ranges but instead you will use the ranges wherever/however you need them. The input date dt, selected from a table input_date in my solution, may instead be a bind variable in your application, etc. Hope you are able to figure out the adjustments yourself; if not, please write back.
with
input_date ( dt ) as (
select to_date('07/01/2014', 'mm/dd/yyyy')
from dual
),
ranges ( date_from, date_to ) as (
select add_months(dt, 12 * (level - 1)) + level - 1,
least(trunc(sysdate), add_months(dt, 12 * level) + level - 1)
from input_date
connect by add_months(dt, 12 * (level - 1)) + level - 1 <= trunc(sysdate)
)
select * from ranges
;
DATE_FROM DATE_TO
---------- ----------
07/01/2014 07/01/2015
07/02/2015 07/02/2016
07/03/2016 11/28/2016

Related

Stored procedure to get one year of data splitted per months

I am relatively new to Oracle so i'd really appreciate some help.
I have a query like:
SELECT * FROM reservations WHERE date between (date1) and (date2).
What I need is to get all the reservations within the interval : today's date and today's date -1 year, so basically 1 year of history.
I want to run the above query with interval of 1 months, and export the query set to excel.
I need some help in the logic of the loop (create a stored procedure or function), as i will think later for the export to excel.
This will give all records from 1 year back to today:
SELECT * FROM reservations
WHERE date >= trunc( sysdate ) - interval '1' year
AND date < trunc( sysdate ) + interval '1' day
I want to run the above query with interval of 1 months,
I understand that you want to run this query 12 times, each time for another monthly period. If yes, then run this query 12 times changing the parameter X (within SELECT 1 As X FROM dual subquery), beginning from 12 to 1 (or 1 to 12):
SELECT * FROM reservations
CROSS JOIN (
SELECT 1 As X FROM dual
) x
WHERE date >= trunc( sysdate ) - x * interval '1' month
AND date < trunc( sysdate ) + interval '1' day - ( x - 1 ) * interval '1' month
Here is the procedure to create the queries month-wise starting from sysdate .
create or replace procedure monthwise_query
as
t_date DATE := TRUNC(SYSDATE) ;
c_date DATE ;
BEGIN
FOR i in 1..12
LOOP
c_date := t_date;
dbms_output.put_line('select * from reservations where rev_date between to_date('''||c_date||''',''DD-MON-YY'') and (select add_months(to_date('''||c_date||''',''DD-MON-YY''),-1) from dual);');
select add_months(c_date,-1)
into t_date
from dual;
END LOOP;
END;
- It can be extended with UTIL_FILE utility inside this procedure to write each query result to single/multiple files.
- SPOOL from SQL*plus for each query will be easy
- UNIX script to loop through each monthwise-query to load to file also possible

Oracle Week Number From Date ISO Week But From December 1

Ok, I've had a query that has been working fine that calculates the week number from December 1 (the start of our Sales Fiscal Year).
Now the requirements have changed. I still need to calculate the week number based on the field (Invoice_Date). However, instead of starting to count from December 1 (Dec 1-7, Week 1, etc.) now I need to start counting on the nearest Monday to December 1st. As I understand it, the ISO week is kind of what I'm looking for but it starts January 1. How do I modify this to work from December 1?
Any help would be greatly appreciated.
select next_day(to_date('0112' || to_char(sysdate, 'YYYY'),'ddmmyyyy') - 1, 'MONDAY') dec_mon from dual; gives you first Monday of December current year
Number of week is just ceil((sysdate - dec_mon)/7).
If you want last Monday before 1st Dec you can get it by:
select next_day(to_date('2511' || to_char(sysdate, 'YYYY'),'ddmmyyyy') - 1, 'MONDAY')
from dual;
In this proposed solution, I build a "helper table" first, showing the Monday_from and Monday_to for each fiscal year (in the third CTE, named ranges). Then I build a few test dates - I was lazy, I should have used to_date() so I can include time-of-day component as well. The join condition in the actual solution (at the end of the code) is written so it works without modification for dates with non-zero "time-of-day" component.
I used the nice feature of Oracle 11.2 which allows us to give column aliases in the declaration of CTEs - otherwise the column aliases would need to be moved inside the respective SELECTs. Otherwise the solution should work at least for Oracle 9 and above (I think).
with
y ( dt ) as (
select add_months(date '2000-12-01', 12 * level )
from dual
connect by level <= 30
),
m ( dt ) as (
select trunc(dt, 'iw') + case when dt - trunc(dt, 'iw') <= 3 then 0 else 7 end
from y
),
ranges ( monday_from, monday_to ) as (
select dt, lead(dt) over (order by dt) - 1
from m
),
test_dates ( t_date ) as (
select date '2013-02-23' from dual union all
select date '2008-12-01' from dual union all
select date '2008-04-28' from dual union all
select date '2016-11-29' from dual
)
select t_date, monday_from, 1 + trunc((t_date - monday_from)/7) as week_no
from test_dates t inner join ranges r
on t.t_date >= r.monday_from and t.t_date < r.monday_to
;
T_DATE MONDAY_FROM WEEK_NO
------------------- ------------------- ----------
2008-04-28 00:00:00 2007-12-03 00:00:00 22
2008-12-01 00:00:00 2008-12-01 00:00:00 1
2013-02-23 00:00:00 2012-12-03 00:00:00 12
2016-11-29 00:00:00 2016-11-28 00:00:00 1
The nearest Monday to any any given date is returned with the following function:
NEXT_DAY(some_date-4,'Monday')
as shown by this query:
with dts(some_date) as (
select date '2006-12-1' from dual
union all
select add_months(some_date,12)
from dts
where some_date <= date '2014-12-1'
)
select some_date
, next_day(some_date-4,'monday') nearest
, some_date - next_day(some_date-4,'monday') dist
from dts;
SOME_DATE NEAREST DIST
----------- ----------- ----------
01-DEC-2006 04-DEC-2006 -3
01-DEC-2007 03-DEC-2007 -2
01-DEC-2008 01-DEC-2008 0
01-DEC-2009 30-NOV-2009 1
01-DEC-2010 29-NOV-2010 2
01-DEC-2011 28-NOV-2011 3
01-DEC-2012 03-DEC-2012 -2
01-DEC-2013 02-DEC-2013 -1
01-DEC-2014 01-DEC-2014 0
01-DEC-2015 30-NOV-2015 1
10 rows selected

Oracle is not working with Japanese OS issue

I have a query which returns second and fourth saturdays of given year,
WITH ALL_SATURDAYS AS
(SELECT TO_CHAR(TO_DATE('01012014','DDMMYYYY'),'WW') * (level) AS WEEK_NO,
NEXT_DAY(TO_DATE('01012014','DDMMYYYY') + (TO_CHAR(TO_DATE('01012014','DDMMYYYY'),'WW' ) * (level-1) * 7),'土') AS SATURDAY_DATE,
row_number() OVER (PARTITION BY TO_CHAR(NEXT_DAY(TO_DATE('01012014','DDMMYYYY') + (TO_CHAR(TO_DATE('01012014','DDMMYYYY'),'WW' ) * (level-1) * 7),'土'),'月') ORDER BY level) AS Pos
FROM DUAL
CONNECT BY level<= 52
ORDER BY 1
)
SELECT SATURDAY_DATE,POS FROM ALL_SATURDAYS WHERE POS IN (2,4) ORDER BY 1,2
It's working in other systems, but mine is a japanese os when i execute this query it returns ORA-01821: date format not recognized error.
How can i fix the error?
Replace 月 with MONTH. The Datetime Format Elements are always in English, even though the results may be in another language.
alter session set nls_date_language=japanese;
select to_char(date '2014-01-01', 'MONTH') month from dual;
Month
-----
1月

Alternate for decode function

I have a table 'Holiday' which lists a set of holiday details.If i specify a date,I should obtain a result date after 5 days of specified date.If there is holiday in between it should exclude them and display the non holiday date.I have table named holiday which includes holiday date,holiday type|(weekly off,local holiday).Now i have used nested decode for continuous holiday checking.Tell me how this can be changed in case function.
DECODE
(date,
holidaydate, DECODE
(date + 1,
holidaydate + 1, DECODE
(date + 2,
holidaydate + 2, DECODE
(date + 3,holidaydate+3,date+4,date+3),date+2),date+1),date);
This can be achieved with a simple subquery which counts the number of holiday dates between a specified date and date+5. The following will return a date that is five non-holiday days in the future:
testdate+(select 5+count(1)
from holiday
where holidaydate between testdate
and testdate + 5)
Simply change both "5"s so another number to change the evaluation period.
SQLFiddle here
Edit - based on comment below, my code doesn't evaluate any days after the fifth day. This would probably be much easier with a function, but the following cte-based code will work also:
with cte as ( (select alldate,holidaydate
from (select to_date('20130101','yyyymmdd')+level alldate
from dual
connect by level < 10000 -- adjust for period to evaluate
) alldates
left join holiday on alldate=holidaydate) )
select
testdate,test_plus_five
from (
select
alldate test_plus_five,testdate,
sum(case when holidaydate is null
then 1
else 0 end) over (partition by testdate order by alldate) lastday
from
cte,
testdates
where
alldate >= testdate
group by
alldate,holidaydate,testdate)
where
lastday = 6
This script builds a calendar table so it can evaluate each day (holiday or non-holiday); then we get a running count of non-holiday days, and use the sixth one.
SQLFiddle here
AFAIK, You can use CASE alternative to DECODE in Oracle
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
Finally i found the optimal solution.Thanks for ur response guys. SELECT dt FROM
(SELECT dt FROM (SELECT TO_DATE('15-AUG-2013','dd-mon-yyyy')+LEVEL dt FROM DUAL
CONNECT BY LEVEL < 30)
WHERE
(SELECT COUNT (*) FROM mst_holiday WHERE holidaydate = dt) = 0 )
where rownum=1

Finding a count of rows in an arbitrary date range using Oracle

The question I need to answer is this "What is the maximum number of page requests we have ever received in a 60 minute period?"
I have a table that looks similar to this:
date_page_requested date;
page varchar(80);
I'm looking for the MAX count of rows in any 60 minute timeslice.
I thought analytic functions might get me there but so far I'm drawing a blank.
I would love a pointer in the right direction.
You have some options in the answer that will work, here is one that uses Oracle's "Windowing Functions with Logical Offset" feature instead of joins or correlated subqueries.
First the test table:
Wrote file afiedt.buf
1 create table t pctfree 0 nologging as
2 select date '2011-09-15' + level / (24 * 4) as date_page_requested
3 from dual
4* connect by level <= (24 * 4)
SQL> /
Table created.
SQL> insert into t values (to_date('2011-09-15 11:11:11', 'YYYY-MM-DD HH24:Mi:SS'));
1 row created.
SQL> commit;
Commit complete.
T now contains a row every quarter hour for a day with one additional row at 11:11:11 AM. The query preceeds in three steps. Step 1 is to, for every row, get the number of rows that come within the next hour after the time of the row:
1 with x as (select date_page_requested
2 , count(*) over (order by date_page_requested
3 range between current row
4 and interval '1' hour following) as hour_count
5 from t)
Then assign the ordering by hour_count:
6 , y as (select date_page_requested
7 , hour_count
8 , row_number() over (order by hour_count desc, date_page_requested asc) as rn
9 from x)
And finally select the earliest row that has the greatest number of following rows.
10 select to_char(date_page_requested, 'YYYY-MM-DD HH24:Mi:SS')
11 , hour_count
12 from y
13* where rn = 1
If multiple 60 minute windows tie in hour count, the above will only give you the first window.
This should give you what you need, the first row returned should have
the hour with the highest number of pages.
select number_of_pages
,hour_requested
from (select to_char(date_page_requested,'dd/mm/yyyy hh') hour_requested
,count(*) number_of_pages
from pages
group by to_char(date_page_requested,'dd/mm/yyyy hh')) p
order by number_of_pages
How about something like this?
SELECT TOP 1
ranges.date_start,
COUNT(data.page) AS Tally
FROM (SELECT DISTINCT
date_page_requested AS date_start,
DATEADD(HOUR,1,date_page_requested) AS date_end
FROM #Table) ranges
JOIN #Table data
ON data.date_page_requested >= ranges.date_start
AND data.date_page_requested < ranges.date_end
GROUP BY ranges.date_start
ORDER BY Tally DESC
For PostgreSQL, I'd first probably write something like this for a "window" aligned on the minute. You don't need OLAP windowing functions for this.
select w.ts,
date_trunc('minute', w.ts) as hour_start,
date_trunc('minute', w.ts) + interval '1' hour as hour_end,
(select count(*)
from weblog
where ts between date_trunc('minute', w.ts) and
(date_trunc('minute', w.ts) + interval '1' hour) ) as num_pages
from weblog w
group by ts, hour_start, hour_end
order by num_pages desc
Oracle also has a trunc() function, but I'm not sure of the format. I'll either look it up in a minute, or leave to see a friend's burlesque show.
WITH ranges AS
( SELECT
date_page_requested AS StartDate,
date_page_requested + (1/24) AS EndDate,
ROWNUMBER() OVER(ORDER BY date_page_requested) AS RowNo
FROM
#Table
)
SELECT
a.StartDate AS StartDate,
MAX(b.RowNo) - a.RowNo + 1 AS Tally
FROM
ranges a
JOIN
ranges b
ON a.StartDate <= b.StartDate
AND b.StartDate < a.EndDate
GROUP BY a.StartDate
, a.RowNo
ORDER BY Tally DESC
or:
WITH ranges AS
( SELECT
date_page_requested AS StartDate,
date_page_requested + (1/24) AS EndDate,
ROWNUMBER() OVER(ORDER BY date_page_requested) AS RowNo
FROM
#Table
)
SELECT
a.StartDate AS StartDate,
( SELECT MIN(b.RowNo) - a.RowNo
FROM ranges b
WHERE b.StartDate > a.EndDate
) AS Tally
FROM
ranges a
ORDER BY Tally DESC

Resources