从sql列中减去日期

时间:2011-10-21 05:34:45

标签: sql date dateadd

再次需要你的帮助

我有一个包含docid列,proposedcompletiondatedocstatus

的sql表
doc_id     ProposedCompdate    Docstatus
0001         2011-10-30           A
0002         2011-11-29           C
0003         2011-10-31           C
0004         2011-10-30           A
0005         2011-10-30           C
0006         2011-10-28           C
0007         2011-10-25           A
0008         2011-10-30           C

现在我想写一个查询来获取Docstatus 'A'的结果,其截止日期应该是当前日期

例如,如果今天的日期是'21 -10-2011'

结果集必须是

doc_id     ProposedCompdate    Docstatus
0001         2011-10-30           A
0004         2011-10-30           A

4 个答案:

答案 0 :(得分:1)

请使用DATEADD SQL SERVER函数,您可以在其中添加或减去日期。

例如,

SELECT DATEADD(day,-9, '2006-06-01') as date_diff;

根据您的问题,查询可能看起来像,

SELECT DATEADD(day,-9, 
   (SELECT ProposedCompdate  FROM Table_name where Docstatus = 'A')) 
AS "-9 Days";

请阅读有关DATEADD函数here !!

的更多信息

答案 1 :(得分:1)

这是假设Microsoft SQL Server,但您的where子句将是:

where Docstatus = 'A' AND DateDiff(day, GETDATE(), ProposedComplete) = 9

DateDiff函数采用测量参数(日,年等),开始日期和结束日期,并返回一个整数。所以今天和ProposedComplete之间的差异应该是9天。

答案 2 :(得分:0)

select doc_id,ProposedCompdate,Docstatus from tableName where convert(varchar(20),ProposedCompdate,101) = convert(varchar(20),dateadd(d,9,getdate()),101) 
and Docstatus='A'

答案 3 :(得分:0)

正常运行sql server 2008

CREATE TABLE #Docs (doc_id varchar(10), ProposedCompdate date,Docstatus  nvarchar(50))

INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0001,'2011-10-30','A')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0002,'2011-11-29','C')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0003,'2011-10-31','C')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0004,'2011-10-30','A')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0005,'2011-10-30','C')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0006,'2011-10-28','C')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0007,'2011-10-25','A')
INSERT INTO #Docs(doc_id, ProposedCompdate, Docstatus) VALUES(0008,'2011-10-30','C')

SELECT * FROM #Docs WHERE CONVERT(DATE, DATEADD(D, 9, GETDATE())) = ProposedCompdate AND Docstatus = 'A'

DROP TABLE #Docs