比较两个列日期返回,如果它们在6个月内

时间:2013-12-18 17:16:10

标签: sql sql-server

这是我的查询。

select distinct m.number --as FirstAccount, m2.number as SecondAccount
from jm_people p
inner join master m on p.accountid = m.number
inner join JM_Subpoena s on m.number = s.number
inner join jm_people p2 on p.pid = p2.pid
inner join master m2 on p2.accountid = m2.number
inner join JM_Subpoena s2 on m2.number = s2.number
and m.number != m2.number

我需要比较s.dateRequesteds2.dateRequested,如果它们在6个月或之内,我需要返回结果。

关于如何做到这一点的任何想法?

例如:

s.dateRequested = '12/18/2013 00:00:000'
s2.dateRequested = '07/27/2013 00:00:000'

它将返回此结果,因为它们在6个月内

s.dateRequested = '12/18/2013 00:00:000'
s2.dateRequested = '03/27/2013 00:00:000'

它不会返回此结果。

1 个答案:

答案 0 :(得分:4)

使用DATEDIFF函数http://technet.microsoft.com/en-us/library/ms189794.aspx

select distinct m.number --as FirstAccount, m2.number as SecondAccount
from jm_people p
inner join master m on p.accountid = m.number
inner join JM_Subpoena s on m.number = s.number
inner join jm_people p2 on p.pid = p2.pid
inner join master m2 on p2.accountid = m2.number
inner join JM_Subpoena s2 on m2.number = s2.number
and m.number != m2.number
WHERE DATEDIFF( mm, s2.dateRequested, s.dateRequested) < 6 OR
DATEDIFF( mm, s2.dateRequested, s.dateRequested) = 6 
AND DATEPART( dd, s2.dateRequested) <= DATEPART( dd, s.dateRequested) 

如果您需要6个月或更短的时间,您可以使用功能DATEPART(天数)和比较天数(6个月或同一天或更短时间)。