get first day of a given week number in oracle - sql

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;
/

Related

SQL: Getting the values of all weekdays of a certain calendar week

I am trying to get the value of bought items of all weekdays of a certain calendar week.
select to_char(angelegt_am, 'Day') angelegt_am,
sum(menge) menge
from fadorders_out
group by to_char(angelegt_am, 'Day');
this Query is giving me all values of the year but i don't know how to change it so i get the data from a certain single week.
Solutions like
where to_char(angelegt_am,'IW') = 44
group by to_char(angelegt_am, 'Day')
have a problem, they return grouped values from all years, not only the current year.
One solution could be this one:
select to_char(angelegt_am, 'Day') angelegt_am,
sum(menge) menge
from fadorders_out
where to_char(angelegt_am, 'IYYY-"W"IW') = '2020-W44'
group by to_char(angelegt_am, 'Day')
Getting the date from a Week (according to ISO-8601) is not trivial, for example 2021-01-04 is Week 53 of year 2020. The year from ISO-Week can be different to the actual year.
For proper conversion I use these functions:
CREATE OR REPLACE FUNCTION ISOWeek2Date(YEAR INTEGER, WEEK INTEGER) RETURN DATE DETERMINISTIC IS
res DATE;
BEGIN
IF WEEK > 53 OR WEEK < 1 THEN
RAISE VALUE_ERROR;
END IF;
res := NEXT_DAY(TO_DATE( YEAR || '0104', 'YYYYMMDD' ) - 7, 'MONDAY') + ( WEEK - 1 ) * 7;
IF TO_CHAR(res, 'fmIYYY') = YEAR THEN
RETURN res;
ELSE
RAISE VALUE_ERROR;
END IF;
END ISOWeek2Date;
CREATE OR REPLACE FUNCTION ISOWeek2Date(WEEK VARCHAR2) RETURN DATE DETERMINISTIC IS
BEGIN
IF NOT REGEXP_LIKE(WEEK, '^\d{4}-?W\d{2}$') THEN
RAISE VALUE_ERROR;
END IF;
RETURN ISOWeek2Date(REGEXP_SUBSTR(WEEK, '^\d{4}'), REGEXP_SUBSTR(WEEK, '\d{2}$'));
END ISOWeek2Date;
Actually you can extract week number from date and then filter using it:
select to_char(angelegt_am, 'Day') angelegt_am,
sum(menge) menge
from fadorders_out
where to_char(angelegt_am, 'iw') = 2 -- specify your week number here
group by to_char(angelegt_am, 'Day')
But please check that you and your DB have the same view on weeks start and end dates
You can further read https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm#i34510
Here you can find all other format arguments accepted by to_char function under the "Datetime Format Models" topic
Filter the data in your where clause, e.g.:
select to_char(angelegt_am, 'Day') angelegt_am,
sum(menge) menge
from fadorders_out
where angelegt_am >= to_date ( :week_start_date, 'yyyy-mm-dd' ) -- change format as appropriate
and angelegt_am < to_date ( :week_start_date, 'yyyy-mm-dd' ) + 7
group by to_char(angelegt_am, 'Day')

Get whole month dates based on day name

I want to get all dates of a month based on day name like if I want to get all FRIDAY dates from current date to a specific end date. I got a solution in SQL but can't find any solution in ORACLE.
You can use hierarchy query with next_day function as follows:
-- input variable
with dataa (start_date, end_date) as
(select date '2020-11-01', date '2020-12-15' from dual)
-- your query starts from here
select next_day((level-1)*7 + (start_date - 1), 'FRIDAY')
FROM DATAA
connect by
next_day((level-1)*7 + (start_date - 1),'FRIDAY') <= end_date
Db<>fiddle here
You can use hierarchical query as
WITH t AS
(
SELECT TRUNC(sysdate,'MM')+level-1 AS Fridays
FROM dual
WHERE TO_CHAR(TRUNC(sysdate,'MM')+level-1,'Dy','NLS_DATE_LANGUAGE=American')='Fri'
CONNECT BY level <= LAST_DAY(TRUNC(sysdate)) - TRUNC(sysdate,'MM') + 1
)
SELECT *
FROM t
WHERE Fridays BETWEEN :data1 AND :date2
Demo
Using connect by then filtering by Friday is a simple solution. In the example below I am using July 1st as the start date and December 1st as the end date.
SELECT DATE '2020-7-1' + LEVEL AS friday_dates
FROM DUAL
WHERE TO_CHAR (DATE '2020-7-1' + LEVEL, 'DY') = 'FRI'
CONNECT BY LEVEL <= DATE '2020-12-1' - DATE '2020-7-1';

Get the last day of each month in the last two years using oracle SQL

I am new to Oracle SQL. I know the LAST_DAY function will return the last day of the month given a specific date. But how can I get the last day of each month in the last two years? Thanks so much!
SELECT TRUNC (ADD_MONTHS (SYSDATE, -(LEVEL - 1)), 'MM') FIRST_DAY,
LAST_DAY (ADD_MONTHS (SYSDATE, -(LEVEL - 1))) LAST_DAY
FROM DUAL
CONNECT BY LEVEL <= 24;
Here you go:
WITH cteTwo_years_ago AS (SELECT TRUNC(SYSDATE - INTERVAL '2' YEAR, 'MONTH') AS TWO_YEARS_AGO
FROM DUAL),
cteMonth_intervals AS (SELECT INTERVAL '1' MONTH * (LEVEL-1) AS SEQ
FROM DUAL
CONNECT BY LEVEL-1 < 24),
cteDates AS (SELECT TWO_YEARS_AGO + SEQ AS MONTH_START
FROM cteTwo_years_ago
CROSS JOIN cteMonth_intervals)
SELECT LAST_DAY(MONTH_START)
FROM cteDates
First and last date of each month in interval from given date up today.
DEFINE start_date=TO_DATE('01.01.2020','DD.MM.YYYY');
SELECT
ADD_MONTHS(&start_date,LEVEL-1) first_day_in_month,
ADD_MONTHS(&start_date,LEVEL)-1 last_day_in_month
FROM DUAL CONNECT BY LEVEL <= FLOOR(MONTHS_BETWEEN(SYSDATE,&start_date));

SQL Oracle How to convert String Week into date

I have dates stored like String in database.
The format is 'yyyy-ww' (example: '2015-43').
I need to get the first day of the week.
I tried to convert this string into date but there is no 'ww' option for the function "to_date".
Do you have an idea to perform this convertion?
EDIT
Test results based on the answers -
Thanks for your anwsers, but I have many problems to apply your solutions to my context:
select
TRUNC ( 2015 + ((43 - 1) * 7), 'IW' )
from dual
==> Error : ORA-01722: invalid number
select
TRUNC(to_date('2015','YYYY')+ to_number('01') *7, 'IW')
from dual
==> 2015-02-02 00:00:00
I waited for a date in january
select
trunc(to_date(regexp_substr('2015-01', '\d+',1,2), 'YYYY') + regexp_substr('2015-01', '\d+') * 7, 'IW') dt2
from dual
==> 0039-09-14 00:00:00
select
regexp_substr('2015-01', '\d+',1,2) as res1,
regexp_substr('2015-01', '\d+') * 7 as res2
from dual
==> res1 = 01
==> res2 = 14105
try to use by truncate
with t as (
select '16-2010' dt from dual
)
--
--
select dt,
trunc(to_date(regexp_substr(dt, '\d+',1,2), 'YYYY') + regexp_substr(dt, '\d+') * 7, 'IW') dt2
from t
I have dates stored like String in database.
You should never do that. It is a bad design. you should store date as DATE and not as a string. For all kinds of requirements for date manipulations Oracle provides the required DATE functions and format models. As and when needed, you could extract/display the way you want.
I need to get the first day of the week.
TRUNC (dt, 'IW') returns the Monday on or before the given date.
Anyway, in your case, you have the literal as YYYY-WW format. You could first extract the year and week number and combine them together to get the date using TRUNC.
TRUNC ( year + ((week_number - 1) * 7)
, 'IW
)
So, the above should give you the Monday of the week number passed for that year.
SQL> WITH DATA AS
2 ( SELECT '2015-43' str FROM dual
3 )
4 SELECT TRUNC(to_date(SUBSTR(str, 1, 4),'YYYY')+ to_number(SUBSTR(str, instr(str, '-',1)+1))*7, 'IW')
5 FROM DATA
6 /
TRUNC(TO_
---------
23-NOV-15
SQL>
Similar to Lalit's, however, I think I've corrected the math (his seemed to be off a bit when I tested .. )
with w_data as (
select sysdate + level +200 d from dual connect by level <= 10
),
w_weeks as (
select d, to_char(d,'yyyy-iw') c
from w_data
)
SELECT d, c, trunc(d,'iw'),
TRUNC(
to_date(SUBSTR(c, 1, 4)||'0101','yyyymmdd')-8+to_char(to_date(SUBSTR(c, 1, 4)||'0101','yyyymmdd'),'d')
+to_number(SUBSTR(c, instr(c, '-',1)+1)-1)*7 ,'IW')
FROM w_weeks;
The extra columns help show the dates before, and after.
I would do the following:
WITH d1 AS (
SELECT '2015-43' AS mydate FROM dual
)
SELECT TRUNC(TRUNC(TO_DATE(REGEXP_SUBSTR(mydate, '^\d{4}'), 'YYYY'), 'YEAR') + (COALESCE(TO_NUMBER(REGEXP_SUBSTR(mydate, '\d+$')), 0)-1) * 7, 'IW')
FROM d1
The first thing the above query does is get the first four digits of the string 2015-43 and truncates that to the closest year (if you convert convert 2015 using TO_DATE() it returns a date within the current month; that is SELECT TO_DATE('2015', 'YYYY') FROM dual returns 01-FEB-2015; we need to truncate this value to the YEAR in order to get 01-JAN-2015). I then add the number of weeks minus one times seven and truncate the whole thing by IW. This returns a date of 01-OCT-2015 (see SQL Fiddle here).
According ISO the 4th of January is always in week 1, so your query should look like
Select
TRUNC(TO_DATE(REGEXP_SUBSTR(your_column, '^\d{4}')||'-01-04', 'YYYY-MM-DD')
+ 7*(REGEXP_SUBSTR(your_column, '\d$')-1), 'IW')
from your_table;
However, there is a problem. ISO year used for Week number can be different than actual year. For example, 1st Jan 2008 was in ISO week number 53 of 2007.
I think a proper working solution you get only when you generate ISO weeks from date value.
WITH w AS
(SELECT TO_CHAR(DATE '2010-01-04' + LEVEL * INTERVAL '7' DAY, 'IYYY-IW') AS week_number,
TRUNC(DATE '2010-01-04' + LEVEL * INTERVAL '7' DAY, 'IW') AS first_day
FROM dual
CONNECT BY DATE '2010-01-04' + LEVEL * INTERVAL '7' DAY < SYSDATE)
SELECT your_Column, first_day
FROM w your_table
JOIN w ON week_number = your_Column;
Your date range must bigger than 2010-01-04 and not bigger than current day.
This is what I used:
select
to_date(substr('2017/01',1,4)||'/'||to_char(to_number(substr('2017/01',6,2)*7)-5),'yyyy/ddd') from dual;

How can I extract and display the date range based on Quarter in Oracle?

I'm building a summary table as part of a stored procedure and I have two columns. The first column needs to show the start and the second column needs to show the end of a date range that is based from an input parameter that is a number designating the quarter. I was able to extract the following from AskTom but I have some questions.
Open C1 FOR
SELECT ( SELECT TRUNC (SYSDATE, 'Q')-1+1 AS 'StartOf' FROM DUAL ),
SELECT ( SELECT TRUNC(ADD_MONTHS (SYSDATE, +3), 'Q')-2 AS 'EndOf' FROM DUAL )
FROM DUAL;
Question 1. Will the Math here account for LeapYears... I don't think it will but I'm not sure how to handle that.
Question 2. How do I add the input parameter, 'inQuarter' as the specific quarter? I've tried putting it in place of sysdate but I need to reformat it into date first I think?
Thanks in advance for any responses.
Tom Kyte has givven you the answer:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:250288900346075009
Open C1 FOR
select add_months( dt, (inQuarter-1)*3 ),
last_day(add_months( dt, (inQuarter-1)*3+2 ) )
from (
select to_date( inYear || '0101', 'yyyymmdd' ) dt
from dual)
You can convert a numeric year and numeric quarter parameter to a DATE
SELECT add_months( trunc( to_date( to_char( <<numeric year>> ),
'YYYY' ),
'YYYY' ),
3 * <<numeric quarter>> ) first_of_quarter,
add_months( trunc( to_date( to_char( <<numeric year>> ),
'YYYY' ),
'YYYY' ),
4 * <<numeric quarter>> ) - 1 last_of_quarter,
FROM dual
The time component of both dates will be midnight on the last day of the quarter (i.e. 24 hours before the beginning of the next quarter). You may want the last of the quarter to be 23:59:59 on the last day of the quarter if you want the range to be inclusive of all possible dates in the quarter.
I suggest:
Open C1 FOR
SELECT TRUNC (d_inQuarter, 'Q') AS "StartOf",
TRUNC(ADD_MONTHS (d_inQuarter, +3), 'Q') AS "EndOf"
FROM (SELECT add_months(to_date(to_char(i_yr)||'-01-01','YYYY-MM-DD'), (i_q-1)*3)
AS d_inQuarter FROM DUAL);
- with integer parameters i_yr and i_q representing the year and quarter, respectively.
Note that EndOf will represent midnight on the first day of the next quarter, so any selection should be based on conditions < "EndOf", not <= "EndOf". (This should ensure that all times on the last day of the quarter are included.)