【问题标题】:SQL query to retrieve data between two dates from two columnsSQL查询从两列中检索两个日期之间的数据
【发布时间】:2017-04-25 16:15:32
【问题描述】:

从两列检索两个日期之间的数据的 SQL 查询

select distinct mname 
from tb_reqmach  
where fromdate >= '2016/12/08' 
  and todate <= '2016/12/30' 
  and mcfact = 'BSC - 3' 
group by mname

当我使用上述查询时,它返回 null。来自 db 的值

The figure attached is the data saved in db

当起始日期和两个日期在保存日期之间时,请帮助检索行

当我使用时

select distinct mname 
from tb_reqmach  
where fromdate >= '2016/12/01' 
  and todate <= '2016/12/30' 
  and mcfact = 'BSC - 3' 
group by mname 

它检索行,当我使用时

select distinct mname, fromdate 
from tb_reqmach  
where '2016/12/08' between fromdate and todate 

这也检索行

但我需要按我的要求检索

【问题讨论】:

  • 您的要求有点不清楚。在您的第一个查询中,您提到了 fromdate>= '2016/12/08' 和 todate
  • 用当前输出和异常输出定义表
  • 比较日期可以使用datediff函数:datediif(d,'2016/12/08', fromdate)>=0 and datediif(d, todate,,'2016/12/30')> =0 。实际上,我认为检查日期范围,每个日期列点需要两个日期
  • 如果fromdate是2016-12-01并且todate是201-12-30保存在db中
  • 如果我选择 2016-12-08 到 2016-12-25 之间的数据,它必须检索保存为 2016-12-01 作为起始日期和 2016-12-30 作为今天的数据

标签: c# sql asp.net sql-server sql-server-2008


【解决方案1】:

试试这个:

select distinct mname 
from tb_reqmach  
where fromdate >= DATEADD(mm, DATEDIFF(mm, 0, '2016/12/08'), 0)
  and todate <= DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, '2016/12/25') + 1, 0)) 
  and mcfact = 'BSC - 3' 
group by mname

如果想分别从fromdate、to date中检索第一天和最后一天的数据,则在条件中使用equal。

【讨论】:

  • 你能解释一下你的代码在做什么吗?
  • 如果我们提供过滤日期为 2016-12-08 到 2016-12-25,那么它将检索 2016-12-01 到 2016-12-31 的数据。
【解决方案2】:

sql 不需要更多! 使用这个:

select distinct mname 
from tb_reqmach  
where fromdate >= '2016/12/08' 
  and mcfact = 'BSC - 3' 
group by mname

然后看看结果: 是否有任何行 (todate

屏幕截图无法在范围内。

【讨论】:

    【解决方案3】:
    select distinct mname 
    from tb_reqmach  
    where fromdate >= convert(datetime, '2016-12-08') 
      and todate <= convert(datetime, '2016-12-30') 
      and mcfact = 'BSC - 3' 
    group by mname
    

    【讨论】:

      【解决方案4】:

      问题是你没有包含你的需求,你只是包含了你认为做你想做的事情的 SQL。

      这个 SQL:

      select distinct mname 
      from tb_reqmach  
      where fromdate >= '2016/12/08' 
        and todate <= '2016/12/30' 
        and mcfact = 'BSC - 3' 
      group by mname
      

      只会获取 fromdate 晚于或等于 12 月 8 日 todate 小于或等于 12 月 30 日的行。您的屏幕截图中没有此类行。

      我的猜测是,您正在寻找可以获取在给定日期范围内有时有效的所有行的东西,这会做到:

      select distinct mname 
      from tb_reqmach  
      where fromdate <= '20161230'
        and todate >= '20161208'
        and mcfact = 'BSC - 3' 
      group by mname
      

      这也是你应该使用的日期格式,其他的会受到区域设置的影响。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-05
        • 2020-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        相关资源
        最近更新 更多