[英]SQL display | select data from today date | current day only
I have this query, it supposes to display data from current date (today) only 我有这个查询,它假设仅显示当前日期(今天)的数据
SELECT * FROM Customer WHERE visitTime <= GETDATE() AND visitTime > GETDATE() - 1
where visitTime is datetime type 其中visitTime是日期时间类型
But it doesn't work well because I think problem is at AND visitTime > GETDATE() - 1
but I don't know how to fix this, anybody has any suggestions? 但这无法正常工作,因为我认为问题出在
AND visitTime > GETDATE() - 1
但是我不知道该如何解决,有人有什么建议吗?
Look at this example: 看这个例子:
declare @visitTime datetime ='2014-10-16 23:59:59.000'
select GETDATE() GETDATE, @visitTime visitTime, GETDATE() - 1 [GETDATE-1]
GETDATE visitTime GETDATE-1
2014-10-17 00:02:18.980 2014-10-16 23:59:59.000 2014-10-16 00:02:18.980
You'll see that the visittime date clearly falls in the range you specified as the lower bound (the -1) subtracts a whole day and not just the time part. 您会看到访问时间日期明显落在您指定的范围内,因为下限(-1)减去一整天,而不仅仅是时间部分。
You could use this instead: 您可以改用以下方法:
-- using GETDATE() for the upper bound misses visitTime that are
-- on the current day, but at a later time than now.
WHERE visitTime < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND visitTime >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)
or if you're on SQL Server 2008+ that has a date
data type, this: 或者,如果您使用的是具有
date
数据类型的SQL Server 2008+,则:
WHERE CAST(visitTime AS DATE) = CAST(GETDATE() AS DATE)
Note that GETDATE()
is T-SQL specific, the ANSI equivalent is CURRENT_TIMESTAMP
注意,
GETDATE()
是T-SQL特定的,ANSI等效是CURRENT_TIMESTAMP
Assuming today is midnight last night to midnight tonight, you can use following condition 假设今天是昨晚午夜至今晚午夜,则可以使用以下条件
Select * from Customer where
visitTime >= DateAdd(d, Datediff(d,1, current_timestamp), 1)
and
visitTime < DateAdd(d, Datediff(d,0, current_timestamp), 1);
SELECT * FROM Customer WHERE visitTime > = convert(date,getdate())
and visitTime < dateadd(d,1,convert(date,getdate()))
Check this out 看一下这个
select *
from Customers
where convert(date,createddate) = convert(date,getdate());
仅获取迄今为止的详细信息:
SELECT * FROM PRODUCTION WHERE CAST(CREATIONDATE AS DATE) = CAST(GETDATE() AS DATE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.