NEWBIE警告! 我正在尝试创建查询以查找特定日期的对象。例如,我希望看到为1/20/17而且仅在今天打印的记录。我可以在一个范围内做到这一点没有问题,但我正在努力弄清楚如何做一天。 任何见解都表示赞赏! 谢谢!
ssrs报告结果
sql studio结果
答案 0 :(得分:1)
如果您的print_date
是datetime
字段而不仅仅是date
,则需要考虑time
元素。我的意思是2017-01-20 13:48:00
实际上并不等于2017-01-20
,因为SQL Server偷偷加上00:00:00
的时间,而且两者不再匹配。
要解决此问题,您可以将datetime
值转换为date
或全部转换为同一时间,但这会降低查询优化器提高查询效率的能力,因为需要读取和转换然后进行比较。
相反,为了不降低优化程序的速度,您需要保留所谓的SARGability并简单地将datetime
值与其他datetime
值进行比较:
declare @sdate date -- Remember that date types add 00:00:00 when compared to datetime.
set @sdate ='20172001' -- Make this the date you want values for.
declare @edate date
set @edate ='20172002' -- Make this the day *after* the date you want values for.
-- To save changing two values, you could just calculate
-- this value using dateadd(d,1,@sdate).
select i.print_date
from dbo.WC_view_bill_hdr as i
join dbo.WC_view_customer as c
on i.customer_id = c.customer_id
join WC_view_bill_batch as ib
on ib.bill_batch_uid = c.bill_batch_uid
where i.print_date >= @sdate -- All values from the very start of this date.
and i.print_date < @edate; -- but that are less than the day after.
如果以这种方式进行日期比较,SQL Server可以最有效地使用您在表上的任何索引,并为更准确的datetime
值添加一定程度的未来验证:
例如,datetime
仅精确到3毫秒,因此明天(2017-01-21
)之前的最早值将是2017-01-20 23:59:59:997
。如果您将查询设置为between '2017-01-20 00:00:00.000' and '2017-01-20 23:59:59:997'
,则存在3毫秒的差距尚未问题。
但是,如果您移动到datetime2
可以表示大于997毫秒的值,那么您现在明确地并且错误地排除了您不应该的值。
这是一个无限的问题,因为今天的结局并没有价值。在明天开始之前&#39;无法进一步划分为无穷大。
但只需指定Greater than or equal to the start of today
和less than the start of tomorrow
即可确保获得所有内容。
答案 1 :(得分:-1)
这应该有效:
svn