SQL查询今天的日期减去两个月


140

我想在表中选择所有记录,这些记录的输入日期早于2个月。

知道我该怎么做吗?

我还没有尝试过任何东西,但是我在这一点上:

SELECT COUNT(1) FROM FB WHERE Dte > GETDATE()

Answers:


285

如果您使用的是SQL Server,请尝试以下操作:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

根据您的更新,它将是:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

25
如果您使用MySQL,它将变成:MyDate < DATE_ADD(NOW(), INTERVAL -2 MONTH)
Stefan 2014年


3

这样的事情对您有用吗?

SELECT * FROM FB WHERE Dte >= DATE(NOW() - INTERVAL 2 MONTH);

3
这是MySQL的解决方案,他要求SQL Server的解决方案。它不适用于SQL Server。
甘德

0
SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

0

TSQL,使用变量声明的替代方法。(这可能会提高查询的可读性)

DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.

SELECT 
        *
    FROM 
        FB as A
    WHERE
        A.Dte <= @gapPeriod;                               --only older records.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.