Gaps between dates Query
Hi,
I needed to compute the gap time between employments for my database. The problem I am running into right now is I am computing unnecessary calculations. For example,
Employment table:
job start date end date
A 13-01-2000 17-09-2002
B 25-02-2003 23-07-2004
C 22-01-2005 15-09-2007
My query is as follows:
SELECT A.job as Job1, B.job as Job2, (B.Start_Date - A.End_Date) as Gap_Time
FROM Employment A, Employment B
WHERE A.Start_Date != B.Start_Date AND A.End_Date != B.End_Date AND A.End_Date < B.Start_Date;
The problem is, I should only be getting the gap times between jobs (A,B) and then (B,C), but my query also computes the gap time between A and C (there shouldn't be one though because C does not directly follow job A so that wouldn't be a gap time between jobs). I've tried to mess around with the different types of joins for the FROM part of the query but still haven't been able to figure this out. Thanks.
Look at the Analytic Functions and specifically the key words LAG and LEAD.
There is a lot of good advice at http://asktom.oracle.com and some demos in Morgan's Library at www.psoug.org.
Similar Messages
-
SQL Lead & Lag to find gap between dates
i have a table with two columns event_start and event_end :
CREATE TABLE MYBATCHTAB
EVENT_START DATE NOT NULL,
EVENT_END DATE NOT NULL
and my data is :
Insert into MYBATCHTAB
(EVENT_START, EVENT_END)
Values
(TO_DATE('08/12/2013 22:45:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/12/2013 23:55:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into MYBATCHTAB
(EVENT_START, EVENT_END)
Values
(TO_DATE('08/12/2013 15:30:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/12/2013 17:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into MYBATCHTAB
(EVENT_START, EVENT_END)
Values
(TO_DATE('08/12/2013 16:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/12/2013 17:30:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into MYBATCHTAB
(EVENT_START, EVENT_END)
Values
(TO_DATE('08/12/2013 20:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/12/2013 22:00:00', 'MM/DD/YYYY HH24:MI:SS'));
COMMIT;
Event Start
Event End
08/12/2013 15:30:00
08/12/2013 17:00:00
08/12/2013 16:00:00
08/12/2013 17:30:00
08/12/2013 20:00:00'
08/12/2013 22:00:00
08/12/2013 22:45:00
08/12/2013 23:55:00
and i want to find the first whole start - end period in this example start : 15:30 - end 17:30 (merging record 1&2 )
but not the third one for example not 15.30 - 22:00 or not 15.30 23:55 because there are gaps between end dates.
how can i do this using lead&lag ?
I'm not sure if this is the best approachMaybe a baby-step solution
select event_start,event_end
from (select event_start,
case when overlap is not null
then case when lead(overlap,1) over (order by event_start) is not null
then lead(event_end,1) over (order by event_start)
when lag(overlap,1) over (order by event_start) is not null
then null
end
else event_end
end event_end
from (select event_start,event_end,
case when lead(event_start,1) over (order by event_start) <= event_end
or lag(event_end,1) over (order by event_start) >= event_start
then 'overlap'
end overlap
from mybatchtab
where event_end is not null
order by event_start
EVENT_START
EVENT_END
08/12/2013 15:30:00
08/12/2013 17:30:00
08/12/2013 20:00:00
08/12/2013 22:00:00
08/12/2013 22:45:00
08/12/2013 23:55:00
or when there can be more than two consecutive overlaps
select event_start,
event_end
from (select case when lag_overlap is null
then event_start
end event_start,
case when coalesce(lead_overlap,lag_overlap) is null
then event_end
when lag_overlap is null and lead_overlap is not null
then lead(event_end) over (order by event_start)
end event_end
from (select event_start,event_end,
case when event_start < lag(event_end) over (order by event_start)
then 'overlap'
end lag_overlap,
case when event_end > lead(event_start) over (order by event_start)
then 'overlap'
end lead_overlap
from mybatchtab
where lead_overlap is null
or lag_overlap is null
where event_end is not null
and event_end is not null
order by event_start
Regards
Etbin -
Dear Experts, I am new to PL/SQL and need your expert advice and help on below query,
SELECT * FROM SCHEMA.TABLE
WHERE DATETIME BETWEEN (TO_DATE('SYSDATE-1 07:00:01','MM/DD/YYYY, HH24:MI:SS')) AND (TO_DATE('SYSDATE-1 14:59:59','MM/DD/YYYY, HH24:MI:SS'));
I want to automate above query which will select yesterday data from mentioned starttime (07:00:01) to endtime (14:59:59).
Please help.
BR,Hi,
DBA wrote:
I am using below duration in between to get a complete day duration data (of yesterday),
DTIME BETWEEN TRUNC(SYSDATE-1) + 0/24 + 1/12/60/60 AND TRUNC(SYSDATE-1) + 23/24 + 1799/12/60/60
Is it valid for a complete one day duration (of yesterday)?
Please help in clarifying this confusion.
Bundle of thanks!If you have to ask, then that means it will be hard to debug and maintain.
Here's a simpler way to find rows where dttime is after 7:00 AM yesterday, but before 3:00 PM yesterday:
WHERE dtime > TRUNC (SYSDATE - 1) + ( 7 / 24)
AND dtime < TRUNC (SYSDATE - 1) + (15 / 24)This will pick rows where dtime is as little as 1 second after 7:00 AM, but not 7:00 AM itself. If you want to include 7:00:00 exactly, change the > to >=. -
Finding gaps between dates in table
Is this following possible in sql...
Lets say I have a "sales" table with these fields
SalesMan, SaleDate, Amount.
and this data
John, 6/may/07,90
John, 4/may/07,330
John, 2/may/07,200
John, 9/apr/07,300
John, 5/apr/07,300
Dave, 9/jul/07,90
Dave, 8/jul/07,90
Dave, 4/jul/07,330
Dave, 2/jul/07,200
Dave, 4/jun/07,300
Dave, 2/jun/07,300
I want to ask the database "show me the third sale made by each sales man after any 2 week gap in sales"
Here's the same data again...
John, 6/may/07,90 --- I want this one
John, 4/may/07,330
John, 2/may/07,200
<2 week gap>
John, 9/apr/07,300
John, 5/apr/07,300
Dave, 9/jul/07,90
Dave, 8/jul/07,90 --- and this one
Dave, 4/jul/07,330
Dave, 2/jul/07,200
<2 week gap>
Dave, 4/jun/07,300
Dave, 2/jun/07,300
My actual problem is more complicated but this is it in its most basic form.
Any help is much appreciated.That's easy enough using the LAG analytic funtion.
with testdata as (select 'John' name, to_date('6/may/07') sdate, 90 amount from dual
union all select 'John', to_date('4/may/07'), 330 from dual
union all select 'John', to_date('2/may/07'), 200 from dual
union all select 'John', to_date('9/apr/07'), 300 from dual
union all select 'John', to_date('5/apr/07'), 300 from dual
union all select 'Dave', to_date('9/jul/07'), 90 from dual
union all select 'Dave', to_date('8/jul/07'), 90 from dual
union all select 'Dave', to_date('4/jul/07'), 330 from dual
union all select 'Dave', to_date('2/jul/07'), 200 from dual
union all select 'Dave', to_date('4/jun/07'), 300 from dual
union all select 'Dave', to_date('2/jun/07'), 300 from dual
), sales_gaps AS (
select name, sdate, amount,
lag(sdate,2) over (partition by name order by sdate, amount) -
lag(sdate,3) over (partition by name order by sdate, amount) delta
from testdata
SELECT NAME, SDATE, AMOUNT FROM SALES_GAPS WHERE DELTA >= 14
NAME SDATE AMOUNT
Dave 08-JUL-2007 12:00:00 90
John 06-MAY-2007 12:00:00 90
2 rows selected -
Select Record Between Date Gap-Oracle 11g, Windows 2008 server
hello everyone,
I have a sql query where I need to select only records with an 18 month gap between max(date) and previous date( no dates between max(date)
and 18 month gap date), when I run the below query it should only select supid 130, not 120 (even though 120 does contain an 18 month gap date it also has a date that is less then the 18 month gap( '25-NOV-2012','DD-MON-YYYY').
how would get the query to look back 18 months for the next date and evaluate the month_between.
any help is greatly appreciated.
example:
create table supply(supID number(8), supply varchar2(20), supdate Date,supamount number(13,2));
insert into supply values(100,'Tapes',to_date('01-AUG-2013','DD-MON-YYYY'),50.00);
insert into supply values(100,'TV',to_date('01-APR-2013','DD-MON-YYYY'),250.00);
insert into supply values(100,'Discs',to_date('25-DEC-2012','DD-MON-YYYY'),25.00);
insert into supply values(120,'Tablets',to_date('25-AUG-2013','DD-MON-YYYY'),15.00);
insert into supply values(120,'Paper',to_date('25-NOV-2012','DD-MON-YYYY'),35.00);
insert into supply values(120,'Clips',to_date('20-NOV-2010','DD-MON-YYYY'),45.00);
insert into supply values(120,'Binders',to_date('28-FEB-2012','DD-MON-YYYY'),25.00);
insert into supply values(130,'Discs',to_date('25-JUL-2013','DD-MON-YYYY'),75.00);
insert into supply values(130,'Calc',to_date('25-JAN-2012','DD-MON-YYYY'),15.00);
insert into supply values(130,'Pens',to_date('15-DEC-2011','DD-MON-YYYY'),55.00);
select * from supply p where to_char(p.supdate,'yyyy')='2013'
and p.supid in(select s.supid from supply s where months_between(s.supdate,p.supdate)<-18)
SUPID SUPPLY SUPDATE SUPAMOUNT
120 Tablets 25-AUG-13 15
130 Discs 25-JUL-13 75Something like this?
select
from (
select
supid
, supply
, supdate
, supamount
, lead(supdate) over (partition by supid order by supdate desc) ldate
from supply
where
months_between(supdate,ldate) >= 18
SUPID
SUPPLY
SUPDATE
SUPAMOUNT
LDATE
130
Discs
07/25/2013
75
01/25/2012
Ok. i see you want only he diff to max date.
select
from (
select
supid
, supply
, supdate
, supamount
, lead(supdate) over (partition by supid order by supdate desc) ldate
, row_number() over (partition by supid order by supdate desc) rn
from supply
where
months_between(supdate,ldate) >= 18
and
rn = 1
Message was edited by: chris227
extended -
Find gap between two dates from table
Hello All,
I want to find gap between two dates ,if there is no gap between two dates then it should return min(eff_dt) and max(end_dt) value
suppose below data in my item table
item_id eff_dt end_dt
10 20-jun-2012 25-jun-2012
10 26-jun-2012 28-jun-2012 There is no gap between two rows for item 10 then it should return rows like
item_id eff_dt end_dt
10 20-jun-2012 28-jun-2012
item_id eff_dt end_dt
12 20-jun-2012 25-jun-2012
12 27-jun-2012 28-jun-2012 There is gap between two rows for item 12 then it should return like
item_id eff_dt end_dt
12 20-jun-2012 25-jun-2012
12 27-jun-2012 28-jun-2012
I hv tried using below query but it giv null value for last row
SELECT item_id, eff_dt, end_dt, end_dt + 1 AS newd,
LEAD (eff_dt) OVER (PARTITION BY ctry_code, co_code, item_id ORDER BY ctry_code,
co_code, item_id) AS LEAD,
(CASE
WHEN (end_dt + 1) =
LEAD (eff_dt) OVER (PARTITION BY ctry_code, co_code, item_id ORDER BY ctry_code,
co_code, item_id, eff_dt)
THEN '1'
ELSE '2'
END
) AS new_num
FROM item
WHERE TRIM (item_id) = '802'
ORDER BY ctry_code, co_code, item_id, eff_dtI m using oracle 10g.
please any help is appreciate.
Thanks.Use start of group method:
with sample_table as (
select 10 item_id,date '2012-6-20' start_dt,date '2012-6-25' end_dt from dual union all
select 10,date '2012-6-26',date '2012-6-26' from dual
select item_id,
min(start_dt) start_dt,
max(end_dt) end_dt
from (
select item_id,
start_dt,
end_dt,
sum(start_of_group) over(partition by item_id order by start_dt) grp
from (
select item_id,
start_dt,
end_dt,
case lag(end_dt) over(partition by item_id order by start_dt)
when start_dt - 1 then 0
else 1
end start_of_group
from sample_table
group by item_id,
grp
order by item_id,
grp
ITEM_ID START_DT END_DT
10 20-JUN-12 26-JUN-12
SQL> SY. -
IIf condition between dates using mdx query
Hi,
how to check IIF condition between dates using mdx query.
I able to check single year,plese check below mdx query.I need to check members between years.
my requirement is member is belongs to between years(2007 to 2010),display "yes" else "NO";
Could you please give me exact mdx query.
From,to-2007,2010,if member belongs to 2007to 2010 then disply "yes"else "no".
how to pass two members in IIf condition.
WITH
MEMBER Measures.[test]
AS Iif([Date].[Calendar Year].currentmember
is [Date].[Calendar Year].&[2007],"no","yes")
SELECT {Measures.[test]}
on 0
,[Product].[Subcategory].[Subcategory].MEMBERS * [Date].[Calendar Year].[Calendar Year]
ON 1
FROM [Adventure Works]
induHi Sriindu,
consider the following:
WITH
MEMBER measures.[test] AS
IIF
Exists
[Date].[Calendar Year].CurrentMember
[Date].[Calendar Year].&[2007] : [Date].[Calendar Year].&[20010]
).Item(0)
IS
[Date].[Calendar Year].CurrentMember
,"yes"
,"no"
SELECT
{measures.[test]} ON 0
[Product].[Subcategory].[Subcategory].MEMBERS
[Date].[Calendar Year].[Calendar Year] ON 1
FROM [Adventure Works];
Philip, -
Can Anyone tell me how to find out the gap between two dates. Specifically Without counting Saturday and Sunday.
corlettk wrote:
<intercession>
Has anyone written a DateMath class?... it would be handy... the amount (and ugliness) of the code required to do elementary date mathematics with the raw Calendar is appaling.<recess>
Isn't Java 7 supposed to cure all this headache?
</recess> -
Hi,
Can any body help to write the query between dates in QAF.
i have writen like this but its is not working
whereClause.append(" OT_DATE between :");
// whereClause.append(++bindCount);
whereClause.append(fromDate);
// whereClause.append(++bindCount);
whereClause.append(" AND :");
whereClause.append(toDate);
ThanxVenkat, u can either use toDate() function in ur sql or use java.sql.Date to convert ur string into date.
Secondly parameters should be passed through whereclauseparams,like
java.sql.Date javaSqlDate =
transaction.getOANLSServices().stringToDate(submitedDateString);
whereClause.append("DATE_COLUMN_NAME = :1");
setWhereClauseParams(0,javaSqlDate);
--Mukul -
two days before my iphone 5 battery was expand and display screen came out and now there has some gap between frame and display.so how it will happen and i already got before months.now i need to backup all the data to icloud before through out.
https://www.dropbox.com/home/iphone
https://www.dropbox.com/home/iphonehttps://www.dropbox.com/home/iphoneMake an appointment at the genius bar of your local Apple Store. The phone has a 1 year warranty. If it's no longer under warranty, a replacement is $269.
-
Query for difference between dates
I know I can use the DATEDIFF
How can I write it if StartDate and EndDate are in these formats?
StartDate: 2006-09-20 00:00:00.000
EndDate: 2013-09-20 18:20:53.000
I want to find the number of days between dates of dates in the two columnsThose work great, What if I want to use values from a table?
I have a column called StartDate and a column called EndDate with dates in it. I just what it to show the StartDate in a column, the Endate in column and the number of days in a column.
Hi,
Based on your description, do you want to display the following result?
USE <DatabaseName>
GO
--Create a table named DateTest
CREATE TABLE DateTest
(StartDate datetime,
EndDate datetime
INSERT INTO DateTest
VALUES ('2006-09-20 00:00:00.000','2013-09-20 18:20:53.000'),
('2007-05-06 12:10:09.000','2008-05-07 12:10:09.000'),
('2007-05-07 09:53:01.000','2009-05-08 09:53:01.000'),
('2008-08-07 05:53:01.000','2010-08-08 05:53:01.000')
-- Create another table named DateTest1
SELECT DateTest.StartDate, DateTest.EndDate,
DATEDIFF(DAY,DateTest.StartDate,DateTest.EndDate) AS days_number INTO DateTest1
FROM DateTest
SELECT *FROM DateTest1
--Below is the result
StartDate EndDate days_number
2006-09-20 00:00:00.000 2013-09-20 18:20:53.000 2557
2007-05-06 12:10:09.000 2008-05-07 12:10:09.000 367
2007-05-07 09:53:01.000 2009-05-08 09:53:01.000 732
2008-08-07 05:53:01.000 2010-08-08 05:53:01.000 731
Thanks,
Lydia Zhang -
Difference between Dates: BW Query???
Hello all,
A.I have to get the difference between dates i.e Date1 and Date2.
I have used a 2 formula variables for each one of them with Replacement path - Key - number as the settings.
When i execute the difference between the 2 formula variables, i get inconsistent results if the dates are from 2 different months.
Example(Correct Result)
Date1 = 14.02.2005
Date2 = 10.02.2005
Result = 4
Example(Incorrect Result)???????
Date1 = 14.02.2005
Date2 = 10.01.2005
Result = 104
Iam know that system is converting the date as a number like 20040214 and 22040110 and just substracts.....This is not correct....any solution to circmvent this problem???
B.If iam using a user-exit for variables, how to pass the values Date1 and Date2 to user-exit so that i can calculate the difference of days using a function module.
I know how to use a user-exit but not sure about working on 2 fields at a time for a formula variable????1) For the first problem, I think you should play with the replacement path settings (type, offset,...). I did this before and I'm sure it worked.
2) If the variables are entered in the variable screen there is no problem to use a function module (it works with steps --> look at the how-to), but I think you want to calculate not on variables but on the keyfigure values itself, in this case you will have to use virtual characteristics. There is also a how-to about this, I can't help you with the details my self.
kr,
Tom -
I am trying to develop a query in MS Access 2010 to join two tables using three joins, one of which is a (between) date range. The tables are contained in Access. The reason
the tables are contained in access because they are imported from different ODBC warehouses and the data is formatted for uniformity. I believe this cannot be developed using MS Visual Query Designer. I think writing a query in SQL would be suiting this project.
ABCPART links to XYZPART. ABCSERIAL links to XYZSERIAL. ABCDATE links to (between) XYZDATE1 and ZYZDATE2.
[ABCTABLE]
ABCORDER
ABCPART
ABCSERIAL
ABCDATE
[ZYXTABLE]
XYZORDER
XYZPART
XYZSERIAL
XYZDATE1
XYZDATE2Thank you for the looking at the post. The actual table names are rather ambiguous. I renamed them so it would make more sense. I will explain more and give the actual names. What I do not have is the actual data in the table. That is something I don't have
on this computer. There are no "Null" fields in either of the tables.
This table has many orders (MSORDER) that need to match one order (GLORDER) in GLORDR. This is based on MSPART joined to GLPART, MSSERIAL joined to GLSERIAL, and MSOPNDATE joined if it falls between GLSTARTDATE and GLENDDATE.
[MSORDR]
MSORDER
MSPART
MSSERIAL
MSOPNDATE
11111111
4444444
55555
2/4/2015
22222222
6666666
11111
1/6/2015
33333333
6666666
11111
3/5/2015
This table has one order for every part number and every serial number.
[GLORDR]
GLORDER
GLPART
GLSERIAL
GLSTARTDATE
GLENDDATE
ABC11111
444444
55555
1/2/2015
4/4/2015
ABC22222
666666
11111
1/5/2015
4/10/2015
AAA11111
555555
22222
3/2/2015
4/10/2015
Post Query table
GLORDER
MSORDER
GLSTARTDATE
GLENDDATE
MSOPNDATE
ABC11111
11111111
1/2/2015
4/4/2015
2/4/2015
ABC22222
22222222
1/5/2015
4/10/2015
1/6/2015
ABC22222
33333333
1/5/2015
4/10/2015
3/5/2015
This is the SQL minus the between date join.
SELECT GLORDR.GLORDER, MSORDR.MSORDER, GLORDR.GLSTARTDATE, GLORDR.GLENDDATE, MSORDR.MSOPNDATE
FROM GLORDR INNER JOIN MSORDR ON (GLORDR.GLSERIAL = MSORDR.MSSERIAL) AND (GLORDR.GLPART = MSORDR.MSPART); -
What is the differences between viewCriteria query modes?
Hello all,
recently we faced a performance issue in a production application. after tracing we found that the issue was caused by setting the query mode of the view criteria to in memory.
bussiness case description:
when creating a new record for table A, I want to populate one field depending on records in another table B, so I used model driven LOV.
The problem was that new records were created for both tables in the same ADF train i.e. the data for both tables were not posted or committed yet.
so by using a query based ViewObject + viewCriteria with query mode set to memory for viewCriteria I managed to populate the LOV with the correct data,
in another page I will show database records for table A with LOV to show meaningful messages to users , but I can as well create new records for table A ,but the loading of this page is very slow.
tracing:
using alter session set sql_trace=true; I found that table B is fully scanned and all rows are fetched-180000+ record-.
Problem description:
from the trace file generated found that the query issued did not have a where clause.
also found that the viewObject fetched the entire table into memory- 180000+ record,- then searched them in memory.
Solution:
changing the query mode of the viewCriteria seems to solve the issue
so in order to avoid such issues in the future ,I wanted to make sure I understand the differences between the query modes of view criteria and their impact on the performance and if there are any differences if the viewObject is based on an entity or a sql dml.
this is what I know so far -please correct me if I am mistaken-:
1)database: search the database appending the conditions of the viewCriteria to whatever the query is
2)memory: search the rows that are already in the memory.
3)both: search both database and memory.
also, in case I updated one of the records in the memory but did not yet post or commit will the fetched rows have the updated values? and if these changes fails the condition from the viewCriteria , will the rows be shown?.The camera roll contains all the photos and videos taken on your device, as well as any saved on your device from the internet, emails, text messages, etc. The photo library contains photos synced to your device from your computer.
Only camera roll photos are synced using iCloud with photo stream. And photo stream only syncs photos, not videos. -
Gap between two characters in SAP Script Address EndAddress.
Hi Abapers,
I have one query regarding Address - EndAddress in SAPScript.
I am putting the code :
/: ADDRESS TYPE '1' PARAGRAPH ZI PRIORITY 'APL43' LINES 6
/:ADDRESSNUMBER &ZPOLGORT-ADRNR&
/:ENDADDRESS
and I am getting the output in this form
<b><i>ABC Soft c/o JSI Hong Kon g
c/o RS Logistics (Shenzhen) Limited
6/F., DZ Zhong Tian Yuan Logistics Ctr.
126/Xia Road, Futian Free Zone,
Shenzhen
China</i></b>
But the problem is there is a gap between character "n" and 'g" in first line in word Kong.
Can anybody suggest me how to solve this issue. Or is there any other issues to sort it out this problem.Hi,
Its not the problem with Address / End Address.
It could be probably maintained that way.
Please check the entry in the table where it is maintained.
reagrds,
Maybe you are looking for
-
How do I change the download files to be the name of the sending file and NOT ViewAttachment?
I started to access my Charter email via Firefox. The names of attachments (Microsoft WORD, PowerPoint and .txt files) appear correctly. However, when I choose to download and save the attachment, the real name is changed to Viewattachment(n) where n
-
Will Nikon Scan 4 run on Mac Pro?
The new Mac Pro will be delivered tomorrow. While gathering as much information as possible about the compatibility of my current programs, I came upon a note on the Nikon website, stating that Nikon Scan 4 is not compatible with Intel Macs. I imagin
-
How do I avoid syncing everything? I want each my devices to vary in their content.
I have a few devices, and I have different uses for each of them. I don't want certain apps on certain devices, and I always end up with apps i don't need or want on my devices. Also, when I put effort into making a playlist on a device, I hate that
-
I can't install flash player on a server in an isolated network.
I have a Win2008 server in an isolated network with no Internet access. I was able to download the newest Flash Player and tried to install it on the server. It fails with the message "actionlist not found". How do I install Flash Player on a system
-
To view the reference sales document of a deleted delivery
Is there a table in SAP where I can see the reference sales document of a deleted delivery? Or is there a way that I can see the reference sales document of a deleted delivery.