【问题标题】:Adding between dates - sql query在日期之间添加 - sql查询
【发布时间】:2020-10-22 23:41:08
【问题描述】:

目前我有一个查询可以获取上个月的数据。

我需要更改此设置,以便我可以选择一个选定的日期范围,以便我输入 2 个日期并拉回它们之间的所有结果。

在下面查看我的查询:

 select * from Table1 I
  inner join Service K on I.Service_Key = K.Service_Key
  inner join Status S on I.Status_Key = S.Status_Key
  where K.Service_Key = '1' 
 and S.Status_Name = 'Closed'
 and month(I.Date_Key) = (select case when Month (GETDATE())-1 = 0 then 12 else Month (GETDATE())-1 end)
 and year(I.Date_Key) =  (select case when Month (GETDATE()) -1 = 0 then year (GETDATE()) -1 ELSE YEAR (GETDATE()) end) 

我需要能够说出 dd/mm/yy 和 dd/mm/yy 之间的日期

【问题讨论】:

  • 旁白:您的日期处理不是sargable,即它不能从Date_Key 上的索引搜索中受益。计算开始和结束日期并使用它们,如 Foster90 和 Linoff 博士的回答,允许索引搜索。

标签: sql tsql


【解决方案1】:

您可以将日期声明为变量:

Declare @Startdate as datetime 
Declare @Enddate as datetime
set @Startdate = '01-AUG-20'
set @Enddate = '22-OCT-20'

select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1' 
and S.Status_Name = 'Closed'
and I.Date_Key > @Startdate
and I.Date_Key < @Enddate 

【讨论】:

    【解决方案2】:

    一个简单的方法是:

    where K.Service_Key = '1' and
          S.Status_Name = 'Closed' and
          datediff(month, i.Date_key, getdate()) = 1
    

    但是,如果合适的话,该版本不能在i.Date_Key 上使用索引。一个对索引更友好的版本是:

    where K.Service_Key = '1' and
          S.Status_Name = 'Closed' and
          i.Date_key < datefromparts(year(getdate()), month(getdate()), 1) and
          i.Date_key >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2010-12-14
      • 2019-02-26
      • 2014-09-23
      • 1970-01-01
      • 2014-12-06
      相关资源
      最近更新 更多