我有一个名为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。
答案 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