查看SQL - 减去日期

时间:2015-04-20 14:48:19

标签: sql sql-server sql-server-2008

我有以下观点

CREATE VIEW dbo.vw_IssueDates AS 
SELECT UserId,
       IssueDate

FROM users 
WHERE IssueDATE <= CONVERT(DATE,  '2015-01-20')
GO
SELECT * FROM dbo.vw_IssueDates

我正在尝试超过30天的优秀罚款列表用户,我知道它将动态涉及GETDATE(所以今天的日期)并减去30但不知道从哪里开始?

2 个答案:

答案 0 :(得分:3)

使用DATEADD(day,-30,GETDATE())

SELECT UserId, IssueDate
FROM users
WHERE IssueDate >= DATEADD(day,-30,GETDATE())

此外,如果您希望在列中显示超过多少天...

SELECT UserId, IssueDate, DATEDIFF(day,IssueDate,GETDATE()) AS DaysOverDue
FROM users
WHERE IssueDate >= DATEADD(day,-30,GETDATE())

答案 1 :(得分:1)

解决此问题的另一种方法是使用datediff函数。您可以这样做:

CREATE VIEW dbo.vw_IssueDates AS 
SELECT UserId,
       IssueDate
FROM users 
WHERE DATEDIFF(day,IssueDATE,getdate()) > 30
GO
SELECT * FROM dbo.vw_IssueDates