SQL时间查询从晚上6点到早上6点

时间:2013-03-19 16:54:06

标签: sql sql-server sql-server-2008

如何计算晚上6点和早上6点后的记录数量?

这可以工作到中午12点。

SELECT distinct count(barcode) c 
FROM table1 
where DAY(timestamp) = DAY(GETDATE())
  AND MONTH(timestamp) = MONTH(GETDATE())
  AND YEAR(timestamp) = YEAR(GETDATE())
  AND datepart(hh,timestamp) >= 18 
  AND datepart(hh,timestamp) >= 6;

3 个答案:

答案 0 :(得分:4)

我想这可能就是你要找的全部。它会从GETDATE()调用中删除任何秒数,并为其添加适当的小时数。

SELECT COUNT(barcode)
FROM table1
WHERE timestamp >= DATEADD(HOUR,18,CONVERT(VARCHAR(10), GETDATE(),110))
  AND timestamp <= DATEADD(HOUR,6,CONVERT(VARCHAR(10), GETDATE()+1,110))

SQL Fiddle Demo

答案 1 :(得分:1)

如果你想在白天计算东西,但要在下午6点开始计算。而不是午夜,只需在时间上添加一个偏移量:

select cast(timestamp + 0.25 as date) as theday, count(barcode)
from table1
group by cast(timestamp + 0.25 as date)
order by theday desc;

如果你想要计算下午6点。 - 下午6点多天:

select cast(timestamp + 0.25 as date) as theday, count(barcode)
from table1
where datepart(hh, timestamp) in (18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5)
group by cast(timestamp + 0.25 as date)
order by theday desc;

最近一天,您可以这样做:

select top 1 cast(timestamp + 0.25 as date) as theday, count(barcode)
from table1
where datepart(hh, timestamp) in (18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5)
group by cast(timestamp + 0.25 as date)
order by theday desc;

答案 2 :(得分:0)

这个怎么样?

  

其中datefunction(timestamp)&gt; = getdate() - 1和(datepart(hh,timestamp)&gt; = 18或   日期部分(11H,时间戳)&LT; = 6)

其中datefunction将datetime转换为日期