sql - Getting all data from last month
问题描述
I am building an SQL view which shows me all entries of table T where the information is last month. I want it so that if I run the view any time in August, it will show me all entries for July, not just a month before which is what I have done with my current code.
Please see this:
where cast(t.Ticket_OpenDate as date) >= cast(dateadd(month, -1, getdate()) as date)
I look forward to hearing from someone.
解决方案
Using DATEDIFF
as in the other answer will not perform well because it cannot use indexes (it is not sarge-able).
It is much better to use a date interval (start and end), in this case we want a half-open interval (exclusive end date):
WHERE t.Ticket_OpenDate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) - 1, 1)
AND t.Ticket_OpenDate < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) , 1)
推荐阅读
- r - `sheets_auth`(来自 `googlesheets4`)不适用于使用 `googleAuthR` 包创建的令牌
- php - 在php中将数组转换为xml
- excel - 使用Word文档中的句子引用提取页码
- node.js - 如何将 node_modules 文件夹添加到现有的角度文件?
- ios - 如何使用 Flutter 在 iOS 中测试验证 InAppPurchase
- java - Android Studio - 不可转换的类型无法将 View 投射到我的活动中
- ffmpeg - H264 解码的最小 FFMPEG 配置选项
- javascript - 聊天准备好后回调
- javascript - highchart漏斗水平
- c# - 解码 json 对象以使其值无法正常工作?