【问题标题】:Sql Server- Get the dates from the database between the range suppliedSql Server - 从提供的范围内的数据库中获取日期
【发布时间】:2019-04-16 07:04:10
【问题描述】:

如果范围(开始日期和结束日期)中任何点的 FtableID 的 StatusID=2,我在获取记录时会遇到问题。

我的表结构是

ID FTableID StatusID AddedOn 75324 53591 1 2019-03-17 06:48:14.490 75325 53591 2 2019-03-18 06:48:14.663 75326 53591 3 2019-03-19 06:54:20.830

@StartDate Datetime='2019/03/17 23:00:00' ,            
@EndDate Datetime='2019/03/20 23:59:59' 

Select ID, FTableID,StatusID,AddedOn from MyTableName where FTableID=53591
And StatusID=2 and AddedOn <= @EndDate 

我知道我的查询是错误的,即使当我通过@startdate 状态更改为 3 (Completed)

我对设置开始日期过滤器感到困惑。

我需要检查此 FtableID 记录在提供的范围内的任何点是否处于状态 id =2

记录应该出现如果我通过了@StartDate Datetime='2019/03/18 23:00:00', @EndDate Datetime='2019/03/20 23:59:59' 因为它在这个范围内它处于状态=2

记录不应该出现如果我通过 @StartDate Datetime='2019/03/19 23:00:00', @EndDate Datetime='2019/03/20 23:59:59' 因为它被转换为状态ID=3

请就此向我提出建议。提前致谢。

【问题讨论】:

  • 嗯,如果你有 @StartDate 变量,那么为什么不在 SQL 中使用它呢? IE。 and AddedOn &gt;= @StartDate 还是@StartDate 在状态 2 的日期时间之后的问题?

标签: sql sql-server


【解决方案1】:

使用这个

select * 
from YourTableName
where AddedOn between (@StartDate and @EndDate)
and StatusID=2

【讨论】:

    【解决方案2】:

    一种方法使用exists。

    我也会简化你的日期运算,所以:

    声明@StartDate datetime '2019-03-17 23:00:00'; 声明@EndDate datetime = '2019-03-20'

    select t.*
    from mytablename t
    where exists (select 1
                  from mytablename t2
                  where t2.ftableid = t.ftableid and
                        t2.statusid = 2 and
                        t2.AddedOn >= @StartDate and
                        t2.AddedOn < @EndDate 
                 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多