SQL选择交叉天数的2倍

时间:2014-07-24 10:10:07

标签: sql sql-server

您好我一直在尝试将SQL查询从昨晚20:00提取到今天上午8点

然而,我只有20:00到24之间选择,因为它只选择昨晚哪种方式可以获得我想要的结果?

SELECT     COUNT(CardID) AS CardCOUNT
FROM         ReaderData
WHERE     (controllerID = 28) AND (ReaderTime BETWEEN '20:00:00' AND '08:00:00') AND (CardID = 'fffffff0') AND (DATEDIFF(DAY, DATEADD(DAY, - 1, 
                  CURRENT_TIMESTAMP), dtReading) = 0)

1 个答案:

答案 0 :(得分:0)

您已将时间与日期分开,因此您必须检查昨天的一个时间间隔和今天的另一个时间间隔。

如果您使用的是SQL Server 2008并且仅在dtReading中存储了日期部分,则可以使用类似的内容。

select count(R.CardID) as CardCount
from ReaderData as R
where controllerID = 28 and
      (
        (
          R.dtReading = cast(dateadd(day, -1, getdate()) as date) and
          R.ReaderTime >= '20:00:00'
        ) or
        (
          R.dtReading = cast(getdate() as date) and
          R.ReaderTime < '08:00:00'
        )
      )

<强>更新

时间值dtReading更容易 通过转换为getdate()date移除时间部分,然后添加您想要创建要比较的datetime值的小时数。

select count(R.CardID) as CardCount
from ReaderData as R
where controllerID = 28 and
      R.dtReading >= dateadd(hour, 20, dateadd(day, -1, cast(cast(getdate() as date) as datetime))) and
      R.dtReading < dateadd(hour, 8, cast(cast(getdate() as date) as datetime))