返回日期差异为一小时的行

时间:2013-09-10 19:47:44

标签: sql-server sql-server-2008 tsql

我有一个名为Payment的表,如下所示:

---------------------------------------------
|PaymentId  |InvoiceId  |Created            |
|-----------|-----------|-------------------|
|10032      |184432     |7/10/2013 11:52am  |
|10033      |184458     |7/10/2013 1:53pm   |
|10034      |184412     |7/12/2013 12:02pm  |
|10035      |184412     |7/12/2013 12:03pm  |
|10036      |184413     |7/13/2013 2:15pm   |
|10037      |184413     |7/13/2013 3:20pm   |
---------------------------------------------

我要做的是创建一个SQL语句,它将返回具有相同InvoiceId的所有行,并且Created DateTime字段的差异大于一小时。

所以在我上面的例子中,我希望返回PaymentId的10036和10037,因为它们共享相同的InvoiceId并且Created字段相隔超过一小时。

PaymentId的10034和10035将不会被退回,因为即使他们共享相同的invoiceid,它们也不会相隔一小时或更长时间。

PaymentId的10032和10033将不会被退回,因为即使它们相隔超过一小时,它们也不会共享相同的InvoiceId。

任何有关写这篇文章的帮助都将不胜感激!

我正在使用SQL Server 2008。

2 个答案:

答案 0 :(得分:1)

SELECT  PaymentID
      , InvoiceID
      , Created
FROM    Payment p
WHERE   EXISTS ( SELECT InvoiceID
                 FROM   Payment p2
                 WHERE  p.InvoiceID = p2.InvoiceID
                 GROUP BY InvoiceID
                 HAVING DATEDIFF(Hour, MIN(Created), MAX(Created)) > 1 ) 

答案 1 :(得分:0)

你可以试试这个:

 select A.* from payment a 
 join payment1 b on a.InvoiceId=b.InvoiceId and datediff(hh,b.Created,a.created)>=1
 union
 select A.* from payment a 
 join payment1 b on a.InvoiceId=b.InvoiceId and datediff(hh,a.Created,b.created)>=1