开发者

Fetch record from a table on date difference

开发者 https://www.devze.com 2023-01-07 11:50 出处:网络
I have data like this. Following is the sample data. alt text http://a.imageshack.us/img695/441/custoemrids.png

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


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
               )


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

精彩评论

暂无评论...
验证码 换一张
取 消