oracle database date operation

Reprinted from http://hi.baidu.com/juanjuan_66/blog/item/cf48554c9331fbe6d62afc6a.html

oracle date subtract
2012-02-10 12:18
--MONTHS_BETWEEN(date2,date1) 
gives month of date2-date1 
SQL>select months_between('19-Dec-1999','19-Mar-1999') mon_between from dual; 

MON_BETWEEN 
----------- 

SQL>select months_between(to_date('2000.05.20','yyyy.mm.dd'),to_date('2005.05.20','yyyy. dd')) mon_betw from dual; 

MON_BETW 
--------- 
-60 

Oracle calculates the time difference expression 

--gets the difference in seconds between two times 
select ceil((To_date('2008-05-02 00:00 :00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2008-04-30 23:59:59' , 'yyyy-mm-dd hh24-mi-ss')) * 24 * 60 * 60 * 1000) FROM DUAL; 
/*  Number of
seconds difference 
---------- 
86401000 
1 row selected 
*/  --Get the number

of seconds difference between two times 
select ceil((To_date('2008-05-02 00:00:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2008-04-30 23:59:59' , 'yyyy -mm-dd hh24-mi-ss')) * 24 * 60 * 60) Difference in seconds FROM DUAL; 
/*  Difference in
seconds 
---------- 
86401 
1 row selected 
*/  --Get

two Time difference in minutes 
select ceil(((To_date('2008-05-02 00:00:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2008-04-30 23:59 :59' , 'yyyy-mm-dd hh24-mi-ss'))) * 24 * 60) Difference in minutes FROM DUAL; 
/*  Difference in
minutes 
---------- 
1441 
1 row selected 
* /  --Get

the difference in hours between two times 
select ceil((To_date('2008-05-02 00:00:00' , 'yyyy-mm-dd hh24-mi-ss') - To_date('2008-04- 30 23:59:59' , 'yyyy-mm-dd hh24-mi-ss' )) * 24) Difference in hours FROM DUAL;
/* 
Difference in hours 
---------- 
25 
1 row selected 
*/  --Get

the difference in days between two times 
select ceil((To_date('2008-05-02 00:00:00' , 'yyyy-mm-dd hh24 -mi-ss') - To_date('2008-04-30 23:59:59' , 'yyyy-mm-dd hh24-mi-ss'))) The difference in days FROM DUAL; 
/* 
The difference in days 
---- ------ 

1 row selected 
*/ 

-------------------------------------- --Note 
: The number of days can be directly reduced by 2 dates, which is more convenient 
----------------------------------- -----  --Get

the month difference between two 
timesselect (EXTRACT(year FROM to_date('2009-05-01','yyyy-mm-dd')) - EXTRACT(year FROM to_date('2008-04-30 ','yyyy-mm-dd'))) * 12 +
EXTRACT(month FROM to_date('2008-05-01','yyyy-mm-dd')) - EXTRACT(month FROM to_date('2008-04- 30', 'yyyy-mm-dd')) months 
from dual; 
/* 
MONTHS 
---------- 
13 
1 row selected 
*/ 

------------------------------- ------- 
Note: You can use the months_between function, which is more convenient 
---------------------------------- ----  --Get the

difference between two time years 
select EXTRACT(year FROM to_date('2009-05-01','yyyy-mm-dd')) - EXTRACT(year FROM to_date('2008-04-30', 'yyyy-mm-dd')) years from dual; 
/* 
YEARS 
---------- 





select sysdate,add_months(sysdate,12) from dual; --add 1 year 
select sysdate,add_months(sysdate ,1) from dual; --add 1 month 
select sysdate,TO_CHAR(sysdate+7,'yyyy-mm-dd HH24:MI:SS') from dual; --add 1 week 
select sysdate,TO_CHAR(sysdate+1, 'yyyy-mm-dd HH24:MI:SS') from dual; --add 1 day 
select sysdate,TO_CHAR(sysdate+1/24,'yyyy-mm-dd HH24:MI:SS') from dual; --add 1 hour 
select sysdate,TO_CHAR(sysdate+1/24/60,'yyyy-mm- dd HH23:MI:SS') from dual; --add 1 minute 
select sysdate,TO_CHAR(sysdate+1/24/60/60,'yyyy-mm-dd HH23:MI:SS') from dual; --add 1 second 

select sysdate+7 from dual; --Add 7 days






to convert the current date to the previous month

SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -1), 'yyyymm') --Get the month before the current time
FROM DUAL;

select sysdate from dual; /**Get current time to seconds**/
select sysdate-3 from dual;/**Get current 2 days**/
select round(sysdate) as format as date from dual;
select to_date('2008- 9-2','yyyy_mm_dd') as format as date from dual;
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -1), 'yyyymm') FROM DUAL; /**--Get the previous month of the current time, forward and backward **/
Select last_day(sysdate) from dual;/**The most popular day of the month**/
/*** Take the year, month and day of the time respectively***/
Select to_char(sysdate,'YYYY') from dual;
select to_char(sysdate,'mm') from dual;
select to_char(sysdate,'dd') from dual;



this is reproduced by Jenry-Yun Feiyang:

1. Last day of last month:
SQL> select to_char(add_months(last_day(sysdate),-1),'yyyy-MM-dd') LastDay from
dual;

LASTDAY
----------
2005-05-31

2. SQL> select to_char( add_months
(sysdate,-1),'yyyy-MM-dd') PreToday from dual;


PRETODAY
----------
2005-05-21

3. The first day of the previous month
SQL> select to_char(add_months(last_day(sysdate)+1,-2),'yyyy-MM-dd') firstDay from dual;

FIRSTDAY
----------
2005-05-01

4. Follow each Statistics for the week
SQL> select to_char(sysdate,'ww') from dual group by to_char(sysdate,'ww');

TO
--
25

5. Statistics are performed monthly.
SQL> select to_char(sysdate,'mm') from dual group by to_char(sysdate,'mm');

TO
--
06

6. According to quarterly statistics
SQL> select to_char(sysdate,'q') from dual group by to_char(sysdate,'q');

T
-
2

7. Statistics are performed by year
SQL> select to_char(sysdate,'yyyy') from dual group by to_char(sysdate,'yyyy');

TO_C
----
2005

8. To find the specific date of all Fridays in a month 
select to_char( td,'YY-MM-DD') from ( 
select trunc(sysdate, 'MM')+rownum-1 as d 
from dba_objects 
where rownum < 
where to_char(td, 'MM') = to_char(sysdate, 'MM') --find the date of Friday of the current month

and trim(to_char(td, 'Day')) = 'Friday' 
----- --- 
03-05-02 
03-05-09 
03-05-16 
03-05-23 
03-05-30 

If you change where to_char(td, 'MM') = to_char(sysdate, 'MM') to sysdate-90, which is the date of finding every Friday in the first three months of the current month.

9. The contents of time operations in oracle

are as follows: 
1. Oracle supports operations on dates. 
2. Date operations are performed in units of days 
.
4. Pay attention to adding parentheses when converting the time base, otherwise there will be problems SQL 

> alter session set nls_date_format='yyyy-mm-dd hh:mi:ss'; The

session has been changed.

SQL> set serverout on 
SQL> declare 
2 DateValue date; 
3 begin 
4 select sysdate into DateValue from dual; 
40 PL/SQL procedure completed successfully. Implementing time addition processing in Oracle -- Name: Add_Times -- Function: Return the result of adding d1 and NewTime to realize the addition of time -- Description: The date in NewTime is not considered -- Date: 2004- 12-07




















-- Version: 1.0
-- Author: Kevin


create or replace function Add_Times(d1 in date,NewTime in date) return date  is
hh
number;
mm number;
ss number;
hours number;
dResult date  ; minutes, seconds select to_number(to_char(NewTime,'HH24')) into hh from dual; select to_number(to_char(NewTime,'MI')) into mm from dual; select to_number(to_char(NewTime,'SS')) into ss from dual; -- Convert the sum of hours in NewTime, in percent hours of a day := (hh + (mm / 60) + (ss / 3600))/ 24; -- Get the result of adding time select d1 + hours into dResult from dual; return(dResult); end Add_Times; -- test case














-- select Add_Times(sysdate,to_date('2004-12-06 03:23:00','YYYY-MM-DD HH24:MI:SS')) from dual


Calculate time difference in Oracle9i
Calculate time difference is Oracle DATA data type a common problem. Oracle supports date calculations, you can create expressions such as "date1 - date2" to calculate the time difference between these two dates. 


Once you've found the time difference, you can use a simple trick to calculate the time difference in days, hours, minutes, or seconds. In order to get the data difference, you must choose the appropriate time measurement unit, so that data format hiding can be done. 

It is tempting to use sophisticated conversion functions to convert dates, but you will find that this is not the best solution. 

round(to_number(end-date-start_date))- elapsed time in days 

round(to_number(end-date-start_date)*24)- elapsed time in hours 

round(to_number(end- date-start_date)*1440) - 

what is the default mode for showing time difference in elapsed time (in minutes)? To find the answer to this question, let's make a simple SQL*Plus query. 

SQL> select sysdate-(sysdate-3) from dual; 

SYSDATE-(SYSDATE-3) 
------------------- 


Here, we see that Oracle uses days as the unit of elapsed time, so we can easily use the conversion function to convert it to hours or minutes. However, when the minutes are not an integer, we run into the problem of placing the decimal point. 

Select 
(sysdate-(sysdate-3.111))*1440 
from 
dual; 

(SYSDATE-(SYSDATE-3.111))*1440 
------------------------ ------ 
4479.83333 

Of course, we can use the ROUND function (that is, the rounding function) to solve this problem, but remember that we must first convert the DATE data type to the NUMBER data type. 

Select 
round(to_number(sysdate-(sysdate-3.111))*1440) 
from 
dual; 

ROUND(TO_NUMBER(SYSDATE-(SYSDATE-3.111))*1440) 
---------------- ------------------------------ 
4480 

We can use these functions to approximately convert an elapsed time to minutes and write this value to in the Oracle table. In this example, we have an off-line (logoff) system-level trigger mechanism to count the session time that has started and put it into an Oracle STATSPACK USER_LOG extension table. 

Update 
perfstat.stats$user_log 
set 
elapsed_minutes = 
round(to_number(logoff_time-logon_time)*1440) 
where 
user = user_id 
and 
elapsed_minutes is NULL;

find out the working days in any year and month
CREATE OR REPLACE FUNCTION Get_WorkingDays(
ny IN VARCHAR2
) RETURN INTEGER IS
/*--- -------------------------------------------------- -------------------------------------
Function name: Get_WorkingDays
Chinese name: Find the middle of a certain year and month How many working days are there?
Author name: XINGPING
Writing time: 2004-05-22
Input parameters: NY: The year and month that contains the number of working days, the format is yyyymm, such as 200405
Return value: Integer value, the number of working days included.
Algorithm description:
1). List each day in the year and month given by the parameter. A table is used here (ljrq is a table in my library. This table can be any table or view with access to at least 31 records) to construct each day of a year and month.
2). Subtract these dates from a date with a known day of the week (2001-12-30 is Sunday), and the difference is modulo 7. If the desired year and month are before 2001-12-30, then the difference obtained is a negative number, and the range of the obtained value after the modulo is greater than -6, less than 0, such as -1 means Saturday, so first add 7 to the result of the modulo, Then find the modulo of 7.
3). Filter out the elements whose values ​​are 0 and 6 in the result set, and then find the count, and the result is the number of working days. 
-------------------------------------------------- ---------------------------------------------------------*/
Result INTEGER;
BEGIN
SELECT COUNT(*) INTO Result
FROM (SELECT MOD(MOD(q.rq-to_date('2001-12-30','yyyy-mm-dd'),7),7) weekday
FROM ( SELECT to_date (ny||t.dd,'yyyymmdd') rq
FROM (SELECT substr(100+ROWNUM,2,2) dd 
FROM ljrq z WHERE Rownum<=31
) t
WHERE to_date(ny||t.dd,'yyyymmdd' ) 
BETWEEN to_date(ny,'yyyymm') 
AND last_day(to_date(ny,'yyyymm'))
)q
) a 
WHERE a. 
RETURN Result; 
END Get_WorkingDays;

______________________________________

There is also a version
CREATE OR REPLACE FUNCTION Get_WorkingDays(
ny IN VARCHAR2
) RETURN INTEGER IS
/*------------------------- -------------------------------------------------- ---------------
Function name: Get_WorkingDays
Chinese name: Find the number of working days in a certain year and month
Author name: XINGPING
Writing time: 2004-05-23
Input parameters: NY: all Find the year and month containing the number of working days, the format is yyyymm, such as 200405
Return value: Integer value, the number of working days included.
Algorithm description: Use the Last_day function to calculate the total number of days in the year and month given by the parameter, and construct a loop based on this value. In this loop, first find the difference between each day of the month and a date known to be Sunday (2001-12-30 is Sunday), and then the difference is modulo 7. If the requested date is before 2001-12-30, then the difference obtained is a negative number, and the value range obtained after the modulo is greater than -6, less than 0, such as -1 means Saturday, so first add 7 to the result of the modulo, and then Find the modulo of 7. If the obtained value is not equal to 0 and 6 (ie not Saturday and Sunday), it counts as a working day. 























The second version requires programming, but no tables or views.
There are still areas that need to be improved in these two versions, that is, festivals are not considered, such as May Day, November, New Year's Day, and Spring Festival, which have not been removed. These holidays should be maintained as a table, and then remove these holidays by looking up the table.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326590681&siteId=291194637