如何在WHERE子句中合并日期范围?

时间:2017-03-17 15:40:29

标签: sql sql-server

我在MS SQL Server中运行以下SQL语句:

SELECT 
    COUNT(*)
FROM 
    [dbo].[QueueAuditTrail] with(nolock)
WHERE
    (queueenddatetime >= '2017-03-17 14:00:00.000' 
     AND queueenddatetime < '2017-03-17 16:36:00.000') 
    AND queuetype = 7
GROUP BY
    queuetype
HAVING
    COUNT(queuetype) < 100000;

queueenddatetime列是UTC格式的时间戳。此SQL语句适用于给定的时间范围;但是,我想配置WHERE语句以反映时间范围介于&#34;大于或等于当前UTC时间减去20分钟&#34;和&#34;小于当前的UTC时间&#34; (使用&#34; YYYY-MM-DD hh:mm:ss.xxx&#34;)格式。怎么办呢?

1 个答案:

答案 0 :(得分:2)

对我来说这看起来像sql-server。

使用dateadd()sysutcdatetime()

select count(*)
from [dbo].[QueueAuditTrail] with(nolock)
where queueenddatetime >= dateadd(minute,-20,sysutcdatetime())
  and queueenddatetime <  sysutcdatetime()
  and queuetype = 7
group by queuetype
having count(queuetype) < 100000
;