I am having two tables TblEnquiry with Enquiry _No as Primary Key and tblHistory for maintaing updatiing details with Enquiry_No as foreign key and History_CreatedOn field for date. I want to get Enquiries which have not been updated since last 7 days.
views:
34answers:
4
+1
A:
If you're using SQL Server:
SELECT
<add columns here>
FROM
tblEnquiry
WHERE
NOT EXISTS
(
SELECT *
FROM tblHistory H
WHERE H.enquiry_no = E.enquiry_no
AND H.history_createdon BETWEEN DATEADD(dy, -7, GETDATE()) AND GETDATE()
)
Tom H.
2010-01-27 20:19:48
Why the BETWEEN? Why not just >= DATEADD(DAY, -7, CURRENT_TIMESTAMP) ?
Aaron Bertrand
2010-01-27 22:37:24
It avoids a situation where there is a date in the future. Ideally the column has a constraint on it that prevents that, but just in case...
Tom H.
2010-01-27 23:17:46
+3
A:
SELECT e.*
FROM tblEnquiry e
WHERE NOT EXISTS(SELECT * FROM tblHistory h WHERE e.Enquiry_No = e.Enquiry_No AND h.History_CreatedOn >= DATEADD(dd, -7, GETDATE())
AdaTheDev
2010-01-27 20:21:25
A:
WITH Hist(enquiry_no, history_createdon) AS
(
SELECT Enquiry_No, History_CreatedOn
FROM tblHistory
WHERE History_CreatedOn >= DATEADD(dd, -7, GETDATE())
)
SELECT *
FROM tblEnquiry
LEFT OUTER JOIN Hist ON tblHist.enquiry_no = tblEnquiry.enquiry_no
WHERE tblHistory.enquiry_no IS NULL
This will avoid the poor performance of the standard NOT EXISTS query
Jeff Hornby
2010-01-27 20:26:21
OP wants enquiries not updated in last 7 days...this will find enquiries without any history
AdaTheDev
2010-01-27 20:29:50
*What* poor performance of NOT EXISTS? http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/ -1 for not understanding SQL
gbn
2010-01-27 20:44:39
Edited to reflect AdaTheDev's comment... as for the poor performance of NOT EXISTS, that's experience
Jeff Hornby
2010-01-27 20:52:23
By all means, test which performs well for you in any given scenario, but the generalisation that performance of NOT EXISTS being poor, full stop, is wrong. The article referenced by @gbn is a very good article - well worth a read - and actually demonstrates the opposite.
AdaTheDev
2010-01-27 21:13:36
most likely the plans for LEFT JOIN, NOT IN and NOT EXISTS will be exactly the same...maybe during the SQL Server 7 days this was the case but since 2000 I really haven't run into this myself..not saying it can't happen
SQLMenace
2010-01-27 21:31:05
A:
Got the answer
select h1.Enquiry_No from tblHistory h1 group by h1.Enquiry_No having DATEDIFF(DD,Max(h1.History_CreatedOn),GETDATE())>=7
I got the Enquiries that have not been updated since last 7 days
Ranjit
2010-01-28 19:40:53