Date calculation, date Calculator

Source: Internet
Author: User

Date calculation, date Calculator

Database environment: Oracle 11g R2

I haven't written a blog for a long time. The main reason is that I have met some of the requirements I have done in my blog before, so I am too lazy to sort them out.

Question: If the number of days in the first week of this month is <= 3 days, the first week will be classified as the previous month.

Implementation ideas:

1. Generate the month corresponding to all dates and dates of the current year, week

2. count the days of each week in each month

3. If the number of days in the first week is <= 3 days, then month-1

The following is an SQL script. The related notes are described in the script.

/* Date of birth and end of year */with x0 as (select to_date ('2017-01-01 ', 'yyyy-mm-dd') as Year of year, to_date ('1970-12-31 ', 'yyyy-mm-dd') as year-end from dual ), /* generate the year-round date */x1 as (select Year-end + level-1 as date from x0 connect by level <= (year-end-year-end) + 1 ), /* calculate the month of the date, week */x2 as (select date, to_char (date, 'mm') as month, to_char (date, 'iw ') as week, to_number (to_char (date, 'D') from x1 ), /* calculate the week and day of the month */x3 as (select date, month, week, dense_rank () over (the month where partition by is located, the week where order by is located) as the week of the month, count (*) over (the month in which partition by is located, the day of the week), the day of the week from x2 ), /* Based on the subject rule, process the month */x4 as (select date, month, week, day of the week, week, case when week of the current month = 1 and day of the week <= 3 then to_number (month)-1 else to_number (month) end nominal month from x3) select nominal month as month, min (date) as month, max (date) as month end from x4 group by nominal month order by 1View Code

Implementation result:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.