简体   繁体   中英

Fetch record from a table on date difference

I have data like this. Following is the sample data.

alt text http://a.imageshack.us/img695/441/custoemrids.png

I want to get all those CustomerIDs which has date diff of 2 hours in DateCreated of Enquiry.

For example CustomerId 10602 has 3 enquiries . If the time difference is 2 hours in any of these three enquiries then this CustomerId should be in my result set. Same for the other Customers.

Thanks

SELECT [CustomerId]
  FROM [Table]
 WHERE [DateCreated] >= DATEADD(hour, -2, GETDATE())
   AND [CustomerId] = xxx;

This presumes that EnquiryId is the PK of the table. I also presumed you want to count items within two hours of each other.

Select Distinct T1.CustomerId
From Table As T1
Where Exists    (
                Select 1
                From Table As T2
                Where T2.CustomerId = T1.CustomerId
                    And T2.EnquiryId <> T1.EnquiryId
                    And Abs(DateDiff(hh, T1.DateCreated, T2.DateCreated)) <= 2
               )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM