【问题标题】:SQL select records with current monthSQL 选择当前月份的记录
【发布时间】:2020-07-21 11:44:55
【问题描述】:

我有一个字段名称教科书日期字段名称 NewMonth
这样的数据

TextBook     NewMonth
ABC          2020-01-01
HDS          2020-01-30 
ZXY          2020-02-15
FGD          2020-02-01
YTS          2020-04-02
HFH          2020-04-05 
EDD          2020-03-25

我的目标是选择当月(2020-04-XX)的记录

TextBook     NewMonth
YTS          2020-04-02
HFH          2020-04-05

我的查询不工作。有人可以纠正我的查询。谢谢

SELECT TextBook, NewMonth
   from  Store
   where NewMOnth >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -1, current_timestamp)), 0)

我认为本月为 -1,过去 2 个月为 -2,过去 3 个月为 -3,依此类推

【问题讨论】:

  • 您真的是指当前月份年,而不是任何一年中的任何日期,比如说,任何一年的四月?

标签: sql sql-server tsql where-clause date-arithmetic


【解决方案1】:

我的目标是选择当月(2020-04-XX)的记录

这是一种选择:

where NewMonth >= datefromparts(year(getdate()), month(getdate()), 1)

如果你也需要一个上限:

where 
    NewMonth >= datefromparts(year(getdate()), month(getdate()), 1)
    and NewMonth < dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

如果你想要上个月:

where 
    NewMonth >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
    and NewMonth < datefromparts(year(getdate()), month(getdate()), 1)

或两个月前:

where 
    NewMonth >= dateadd(month, -2, datefromparts(year(getdate()), month(getdate()), 1))
    and NewMonth < dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2019-11-09
    相关资源
    最近更新 更多