如何查找日期列中的差异为3天或更多天的行?

时间:2015-01-23 17:00:59

标签: comparison operators

如何找到两个日期列之间的差异(如下所示)等于或大于3天的行(我使用的是哪个运算符)?以下示例仅返回大于。我需要将行限制为3天或更多天。然后添加一个显示天差计数的列会很好。我正在使用Microsoft SQL Server Management Studio ver。 11在SQL Server 9上。我搜索了有关时差的问题,但没有找到这种特定情况。感谢您对此的任何帮助。

SELECT        Id, LastContactDate, LastProfileReceivedDate
FROM            Location
WHERE        (Account_Id = '499') AND (LastContactDate > LastProfileReceivedDate)

2 个答案:

答案 0 :(得分:0)

有几种可能的查询可以返回指定的结果。我这样做:

   SELECT l.Id
        , l.LastContactDate
        , l.LastProfileReceivedDate
        , TIMESTAMPDIFF(DAY,l.LastProfileReceivedDate,l.LastContactDate) AS days_diff
     FROM Location l 
    WHERE l.Account_Id = '499'
      AND l.LastContactDate >= LastProfileReceivedDate + INTERVAL 3 DAY

<强>跟进:

上面的SQL查询是针对MySQL的(问题标记为&#34; mysql&#34;),这与Microsoft SQL Server完全不同。

对于Microsoft SQL Server,将MySQL TIMESTAMPDIFF()函数替换为SQL Server DATEDIFF函数,并将+ INTERVAL 3 DAY替换为DATEADD函数:

   SELECT l.Id
        , l.LastContactDate
        , l.LastProfileReceivedDate
        , DATEDIFF(DAY,l.LastProfileReceivedDate,l.LastContactDate) AS days_diff
     FROM Location l 
    WHERE l.Account_Id = '499'
      AND l.LastContactDate >= DATEADD(DAY,3,l.LastProfileReceivedDate)

答案 1 :(得分:0)

我使用了第一个答案中的信息并对其进行了修改并且有效:

SELECT Id AS Dormo_ID,LastContactDate,LastProfileReceivedDate,DATEDIFF(day,LastProfileReceivedDate,LastContactDate)AS Days_Difference 从位置 WHERE(Account_Id ='499')AND(DATEDIFF(day,LastProfileReceivedDate,LastContactDate)&gt; 2)