SQL 日期公式
我需要 Oracle SQL 或 T-SQL 中的日期公式来返回上周的日期(例如上周一的日期)。
我的报告包含每周运行的参数,通常参数日期为前一周的周一至周五或周日至周六。 我不想在每周运行报告时输入日期。
数据位于 Oracle 中,我使用 SQL Server 2005 Reporting Services (SSRS) 来生成报告。
I need a date formula in Oracle SQL or T-SQL that will return a date of the previous week (eg Last Monday's date).
I have reports with parameters that are run each week usually with parameter dates mon-friday or sunday-saturday of the previous week. I'd like to not have to type in the dates when i run the reports each week.
The data is in Oracle and I am using SQL Server 2005 Reporting Services (SSRS) for the reports.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
T-SQL:
您是否也需要时间部分为“00:00:00”?
如果是这样,请将此表达式添加到计算中:
T-SQL:
Do you need the time part to be "00:00:00", too?
If so, add this expression to the calculation:
这是周一的 Oracle 解决方案。
以下是检索上周任何特定日期的示例。
如果您需要时间部分为 00:00:00,请将语句包装在 TRUNC(...) 中。
Here is an Oracle solution for Monday.
Here are examples that retrieve any particular day from the previous week.
If you need the time part to be 00:00:00 wrap the statment in TRUNC(...).
查看这篇文章中的日期函数列表。 你想要这个。
它们几乎总是数学而不是面向字符串的,因此它们比套管或铸造操作工作得更快
Check out the list of date functions in this post. You want this one.
They are almost always math and not string oriented so they will work faster than casing or casted operations
这是我的解决方案,经过 8 天的测试。
这是周日的问题:
许多解决方案为同一周的周日和周一提供相同的答案。 旧的星期一不应该被放弃,直到另一个星期一发生。
Here's my solution, tested against 8 days.
Here's the trouble with Sunday:
Many of these solutions Provide the same answer for Sunday and Monday in the same week. The old Monday should not be resigned until another Monday has occurred.
(Oracle)
trunc(sysdate,'IW') --给出本周的星期一
trunc(sysdate,'IW')-7 --给出上周的星期一
这假设您认为星期一是一周的第一天,这就是“IW”(ISO 周)的意思。 如果您认为星期日是一周的第一天...
trunc(sysdate,'W')+1 --给出本周的星期一,星期日这将是未来的
trunc(sysdate,'W')+1 -7 --给出上周的星期一
(Oracle)
trunc(sysdate,'IW') --gives this week's monday
trunc(sysdate,'IW')-7 --gives last week's monday
This assumes you consider monday to be the first day of the week, which is what 'IW' (ISO Week) signifies. If you consider sunday to be the first day of the week...
trunc(sysdate,'W')+1 --gives this week's monday, on sunday this will be in the future
trunc(sysdate,'W')+1-7 --gives last week's monday
在 Oracle 中:
编辑:使其更加简洁
编辑:Leigh Riffel 发布了一个比我的更好的解决方案。
In Oracle:
Edit: Made it a bit more concise
Edit: Leigh Riffel has posted a much better solution than mine.
T-SQL 解决方案:
假设 SET DATEFIRST 为默认值(周日 = 7),上周一的日期:
“-9”表示返回一周 (-7),然后由于周一为 2,我们再减去 2并添加当天是星期几。
A T-SQL solution:
Assuming that SET DATEFIRST is at the default (Sunday = 7), last Monday's date:
The "-9' is to go back one week (-7) and then since Monday is 2 we are subtracting 2 more and adding the day of the week for the current day.