从几个月计算日期

时间:2018-11-02 12:43:29

标签: sql tsql

此表的作用类似于某人工作地点的历史记录。 其中TypeID = 1是当前的工作地点,因此EndDate是今天的日期,StartDate是他们开始的时间,并根据Months列进行计算。

他们以前工作的地方是TypeID = 2,因此EndDate比第一条记录的StartDate要短1天,而TypeID为2的StartDate应该是他们盯着这份工作的时间,即24个月前。

表格格式

create table #test (startdate date, enddate date, months int, typeid int, account int)
insert into #test values (NULL,getdate(), 12, 1, 12345)
insert into #test values (NULL,NULL, 24, 2, 12345)

输出结果

create table #test (startdate date, enddate date, months int, typeid int, account int)
insert into #test values ('2017-11-02',getdate(), 12, 1, 12345)
insert into #test values ('2015-11-1','2017-11-01', 24, 2, 12345)

startdate   enddate     months  typeid  account
2017-11-02  2018-11-02  12      1       12345
2015-11-01  2017-11-01  24      2       12345 

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

评论太久了,但仍然有很多来自问题的假设

#test和#testa应该是不同的表吗?我假设您已正确填充#test,并且可以使用

之类的方法填充#testa
create table #test (startdate date, enddate date, months int, typeid int, account int)
insert into #test values (NULL,getdate(), 12, 1, 12345)
insert into #test values (NULL,NULL, 24, 2, 12345)

create table #testa (startdate date, enddate date, months int, typeid int, account int)

INSERT INTO #testa
SELECT DATEADD(month, months*-1, enddate), enddate, months, typeid, account
FROM #test
WHERE typeid = 1

INSERT INTO #testa
SELECT DATEADD(month, months*-1, DATEADD(day, -1, GETDATE())), DATEADD(day, -1, GETDATE()), months, typeid, account
FROM #test
WHERE typeid = 2

SELECT * FROM #testa

DROP TABLE #test
DROP TABLE #testa

如果不需要#testa,可以通过#test上的更新语句来完成。 这也可以通过单个查询中的case语句来完成。我将其保留为两个,以尝试了解此答案是否在正确的路径上。

相关问题