两个日期之间的差异

发布于 2024-11-30 18:24:34 字数 76 浏览 4 评论 0原文

为了学习,我一直在写一些关于 SQL Server 的查询。

我想知道如何在 SQL 查询中获得今天与 90 天前的差异?

I have been writing some queries about SQL Server in order to learn.

I wonder that how can I get the difference of today between 90 days ago in a SQL query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

只等公子 2024-12-07 18:24:34
DATEDIFF

http://msdn.microsoft.com/en-us/library/ms189794.aspx

DECLARE @90DaysAgo datetime
        ,@Today datetime

SET @90DaysAgo = DATEADD(d, -90, GETDATE())
SET @Today = GETDATE()

SELECT DATEDIFF(d, @90DaysAgo, @Today) --Returns 90
DATEDIFF

http://msdn.microsoft.com/en-us/library/ms189794.aspx

DECLARE @90DaysAgo datetime
        ,@Today datetime

SET @90DaysAgo = DATEADD(d, -90, GETDATE())
SET @Today = GETDATE()

SELECT DATEDIFF(d, @90DaysAgo, @Today) --Returns 90
划一舟意中人 2024-12-07 18:24:34

您需要 DATEADD,而不是 DATEDIFF,并且您需要决定是否需要90 天前:

SELECT DATEADD(day,-90,CURRENT_TIMESTAMP)

或 3 个月前:

SELECT DATEADD(month,-3,CURRENT_TIMESTAMP)

You want DATEADD, not DATEDIFF, and you need to decide whether you need 90 days ago:

SELECT DATEADD(day,-90,CURRENT_TIMESTAMP)

or 3 months ago:

SELECT DATEADD(month,-3,CURRENT_TIMESTAMP)
故笙诉离歌 2024-12-07 18:24:34

尝试返回 90 年前的日期和时间:

SELECT GETDATE()-90

输出:

-----------------------
2011-05-20 10:55:12.360

(1 row(s) affected)

这只会为您提供 90 天前的日期,时间为 00:00:00.000:

SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),-90)

输出:

-----------------------
2011-05-20 00:00:00.000

(1 row(s) affected)

try this to return the date and time for exactly 90 ago:

SELECT GETDATE()-90

output:

-----------------------
2011-05-20 10:55:12.360

(1 row(s) affected)

this will give you the date only for 90 days ago, with a time of 00:00:00.000:

SELECT DATEADD(day,DATEDIFF(day,0,GETDATE()),-90)

output:

-----------------------
2011-05-20 00:00:00.000

(1 row(s) affected)
那小子欠揍 2024-12-07 18:24:34

这将正确舍入到 3 个月前(而不是 90 天前)的午夜,这似乎是您想要的(08-18 -> 05-18 是 92 天,因为那里有两个 31 日)。

...
WHERE column >= DATEADD(MONTH, -3, 
    DATEADD(DAY, DATEDIFF(DAY, '20000101', CURRENT_TIMESTAMP), '20000101'));

This will round correctly to midnight on the day 3 months ago (not 90 days ago) which seems to be what you want (08-18 -> 05-18 is 92 days since there were two 31sts in there).

...
WHERE column >= DATEADD(MONTH, -3, 
    DATEADD(DAY, DATEDIFF(DAY, '20000101', CURRENT_TIMESTAMP), '20000101'));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文