tags:

views:

34

answers:

4

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.

+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.
Why the BETWEEN? Why not just >= DATEADD(DAY, -7, CURRENT_TIMESTAMP) ?
Aaron Bertrand
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.
+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
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
OP wants enquiries not updated in last 7 days...this will find enquiries without any history
AdaTheDev
*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
Edited to reflect AdaTheDev's comment... as for the poor performance of NOT EXISTS, that's experience
Jeff Hornby
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
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
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