Oracle obtains the SQL statement used to query data from the last Monday to the weekend.

Source: Internet
Author: User

Copy codeThe Code is as follows:
-- Oracle reads SQL statements from last Monday to weekend

-- The day of the week starts on Sunday.
Select to_char (to_date ('201312', 'yyyymmdd'), 'D') from dual;
-- Result: Note 6: the sixth day of the week is Friday.

Select to_char (sysdate + (2-to_char (sysdate, 'D')-7, 'yyyymmdd') from dual; --- last Monday
Select to_char (sysdate + (2-to_char (sysdate, 'D')-1, 'yyyymmdd') from dual; --- last Sunday

-- Return the date type in a simpler way
Select trunc (sysdate, 'iw')-7 from dual; --- last Monday
Select trunc (sysdate, 'iw')-1 from dual; -- last Sunday

-- This is Monday.
Select trunc (sysdate, 'iw') from dual;

Select trunc (to_date ('20170101', 'yyyymmdd'), 'aws') from dual;
-- Result: Note: 20130915 is Sunday

-- Returns the char type.
Select to_char (trunc (sysdate, 'iw')-7, 'yyyymmdd') from dual; -- last Monday
Select to_char (trunc (sysdate, 'iw')-1, 'yyyymmdd') from dual; -- last Sunday

-- Obtain the function of last Monday
Create or replace function fun_acc_getlastweekstart (systemdate in date)
Return varchar2 is
Result_str varchar2 (15 );
Begin
Select to_char (trunc (systemdate, 'iw')-7, 'yyyymmdd ')
Into result_str
From dual;
Return result_str;
End fun_acc_getlastweekstart;

-- Obtain the function of last Sunday
Create or replace function fun_acc_getlastweekend (systemdate in date) return varchar2 is
Result_str varchar2 (15 );
Begin
Select to_char (trunc (systemdate, 'iw')-1, 'yyyymmdd ')
Into result_str
From dual;
Return result_str;
End fun_acc_getlastweekend;

-- Test this function.
Select fun_acc_getlastweekstart (sysdate) from dual;
Select fun_acc_getlastweekend (sysdate) from dual;
Select fun_acc_getlastweekstart (to_date ('201312', 'yyyymmdd') from dual;
Select fun_acc_getlastweekend (to_date ('201312', 'yyyymmdd') from dual;
-- Query results: 20130826, 20130901, 20130902, and 20130908
-- Note:
Select sysdate from dual;
-- Query Result: 9:45:14

Related Article

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.