【问题标题】:sql, get date within a range but also using getDatesql,获取范围内的日期,但也使用getDate
【发布时间】:2019-09-15 03:11:48
【问题描述】:

我想获取介于某些日期之间的日期,但我还需要使用 GETDATE 函数,因为它必须是从去年 12 月 1 日到今年 3 月 31 日 我只是可以连接日期并将它们放在一个 between 语句中

[编辑] 我正在使用 sql server,我拥有的代码如下

select c.nombre, p.folio, pg.fecha, pg.monto
from Cliente c, Contratante ct, póliza p, Pago pg
where c.IdCli = ct.IdCli and p.IdCli = ct.IdCli and p.folio = pg.folio  


我得到以下结果

Jorge González  300 2018-12-20 00:00:00.000 10000,00
Jorge González  300 2019-06-30 00:00:00.000 7000,00
Alejandro Lara  310 2018-12-30 00:00:00.000 8000,00
Francisco Hernández 320 2019-03-31 00:00:00.000 5000,00
Marcela Ocampo  330 2019-06-30 00:00:00.000 5000,00

我只想获得 2018-12-01 和 2019-03-31 之间的那些 但我需要使用当前年份作为参考来做这件事

【问题讨论】:

  • 你使用的是哪个数据库 Sql server 或 mysql ?和表格的设计,也许还有一些数据也非常有用,最终结果应该是什么样子
  • @nbk mysql 没有 getdate(),ms sql server 有。
  • 您可以在 SQL Server 中使用 getdate() 和 dateadd()。您可以使用 convert() 转换为日期时间类型。您可以使用 month() 获取月份和 year() 从 getdate() 获取年份。
  • 我上传了一些信息作为编辑
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(25 多年前),不鼓励使用它

标签: sql sql-server


【解决方案1】:

以下将为您提供“20181201”:

select convert(char(4), year(getdate()) - 1) + '12' + '01'

和“20190331”:

select convert(char(4), year(getdate())) + '03' + '31'

【讨论】:

    【解决方案2】:

    您可以使用 getdatefromparts、year 和 getdate 的组合:

    下面给你2108-12-01

    select datefromparts(year(getdate())-1,12,1) 
    

    以下给你2019-03-31

    select datefromparts(year(getdate()),3,31)
    

    【讨论】:

    • 我认为这是这个问题的最佳答案。
    【解决方案3】:

    如果日期是静态的,最好的办法是结合使用 extractgetdate 函数。

    select * from my_table
    where my_date between 
      convert(date, year(getdate() - 1) + '-12-01') 
      and convert(date, year(getdate()) + '-03-01')
    

    【讨论】:

    • EXTRACT() 在 SQL Server 中?它在 MySQL 而不是 SQL Server 中可用。
    • @Sami:Doh!你是绝对正确的。我与一堆数据库一起工作,有点搞混了。谢谢。 :)
    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多