Hello,
First time posting on the forum but a long time searcher!! I'm having some problems writing efficient code to complete what I think should be a relatively simple scenario. I have a table with a Name and then a Timestamp column as a Contact_DateTime. For every occurence of a Name and a Contact Date I want to a third column showing the number of Contact_DateTime appears within 7 days of the original Contact_DateTime excluding the original Contact_DateTime
Sample Contact table
Name|Contact_DateTime
Frank|04/04/2012 20:00:00
Dave|05/04/2012 20:00:00
Dave|06/04/2012 20:00:00
Frank|12/04/2012 20:00:00
Desired Query Output
Name|Contact_DateTime|Contact_7Days
Frank|04/04/2012 20:00:00|0
Dave|05/04/2012 20:00:00|1
Dave|06/04/2012 20:00:00|0
Frank|12/04/2012 20:00:00|0
My first attempt of the code is below which does works but then I have the problem of aggregating the data to get the desired output. If I waited the estimated time to run I thinK I would have aged 2 years!
Select Contact_ALL.Name, Contact_ALL.DateTime, Contact_7.DateTime as OtherDateTime, (Contact_ALL.DateTime + Interval '7' Day) as DateTime7,
Case
When Contact_7.Contact_DateTime= Contact_ALL.Contact_DateTime then 0
When Contact_7.Contact_DateTime Between Contact_ALL.Contact_DateTime and DateTime7 Then 1
Else
0 End as Contact_7Days
From Database.Contact Contact_ALL
Inner Join (Select Contact.Name, Contact.Contact_DateTime from Database.Contact) Contact_7
On
Contact_ALL.Name= Contact_7.Name
Order by 1,2,3
Apologies if I'm not following any structure but I'm happy to listen to suggestions and improvements. I'll try respond in the correct manner too.
Thanks in advance
Dave
Forums: