简体   繁体   中英

Create Custom Week Of Field SQL -- Oracle 12c

This is for a query in Oracle 12c

I'm trying to create a "Week Of" field that will use the date field present in the record to assign that record a Week Of date that reflects the start of a week. I want the start of weeks to be Sundays and the end of weeks to be Saturdays.

To give an example of what I mean:

metric_date        metric        value        week_of
01-oct-20          sales         45           27-sep-20
05-oct-20          sales         15           04-oct-20

Where the week of field is always the most recent sunday date. I have tried to modify this SQL Server code to work in Oracle, as it was written for a similar purpose:

SELECT DATEADD(DAY, -DATEDIFF(DAY, 0, [Order Date]) % 7, [Order Date]) AS [Week of]
FROM dbo.your_table_name

Here is my attempt at replicating the code in Oracle:

SELECT distinct
metric_date,
mod(-(to_date('01-jan-1900','dd-mon-yyyy') - trunc(metric_date)),7) + metric_date as week_of

FROM dbo.table

But it does not return the results I want. Are there any obvious differences you can see that I am not accounting for in my replicated code?

You could use next_day() :

select t.*, next_day(metric_date - 7, 'sunday')
from mytable t

Note that the second argument to next_day() is language-dependent. If your database is configured in another language than English, use the local translation of Sunday.

You can use TRUNC with the IW option (which is independent of the language) to truncate the date to Monday and then shift the values by 1 day:

SELECT metric_date,
       TRUNC( metric_date + INTERVAL '1' DAY, 'IW' ) - INTERVAL '1' DAY
         AS sunday_of_week
FROM   table_name

Which, for the sample data:

CREATE TABLE table_name ( metric_date ) AS
SELECT DATE '2020-10-01' + LEVEL - 1
FROM   DUAL
CONNECT BY LEVEL <= 14;

Outputs:

\nMETRIC_DATE |  SUNDAY_OF_WEEK \n:---------- |  :------------- \n01-OCT-20 |  27-SEP-20      \n02-OCT-20 |  27-SEP-20      \n03-OCT-20 |  27-SEP-20      \n04-OCT-20 |  04-OCT-20      \n05-OCT-20 |  04-OCT-20      \n06-OCT-20 |  04-OCT-20      \n07-OCT-20 |  04-OCT-20      \n08-OCT-20 |  04-OCT-20      \n09-OCT-20 |  04-OCT-20      \n10-OCT-20 |  04-OCT-20      \n11-OCT-20 |  11-OCT-20      \n12-OCT-20 |  11-OCT-20      \n13-OCT-20 |  11-OCT-20      \n14-OCT-20 |  11-OCT-20      \n

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM