3

如何计算晚上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;
4

3 回答 3

9

我想这可能就是你要找的全部。它从 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 小提琴演示

于 2013-03-19T17:04:59.697 回答
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;
于 2013-03-19T17:49:50.233 回答
0

这个怎么样?

其中 datefunction(timestamp)>=getdate()-1 和 (datepart(hh,timestamp)>=18 或 datepart(hh,timestamp)<=6)

其中 datefunction 将日期时间转换为日期

于 2013-03-19T17:11:31.290 回答