我正在使用SQL SERVER 2008.我有一个名为Cut-Off
表的表。此表仅显示每个月的StartDate
截止日期。所以我正在创建一个临时表,用于存储StartDate
,EndDate
,Month
和Year
。但我不知道如何通过EndDate
获取datetime
。
表格
----------------------------------------------------------
StartDate EndDate Month Year
----------------------------------------------------------
2014-12-15 00:00:00 NULL 12 2014
2015-01-26 00:00:00 NULL 1 2015
2015-02-26 00:00:00 NULL 2 2015
---------------------------------------------------------
预期输出
--------------------------------------------------------------------
StartDate EndDate Month Year
------------------------------------------------------------------
2014-12-15 00:00:00 2015-01-25 23:59:99 12 2014
2015-01-26 00:00:00 2015-02-25 23:59:99 1 2015
2015-02-26 00:00:00 2015-03-25 23:59:99 2 2015
------------------------------------------------------------------
我如何获得EndDate?
答案 0 :(得分:1)
'23:59:99'无法获得99秒
试试这个:
CREATE TABLE #temp(StartDate datetime, EndDate datetime, Month int, Year int)
INSERT #temp values
('2014-12-15 00:00:00', NULL, 12, 2014),
('2015-01-26 00:00:00', NULL, 1, 2015),
('2015-02-26 00:00:00', NULL, 2, 2015)
UPDATE t
SET EndDate = DateAdd(m, DateDiff(m, 0, StartDate), '1900-02-25T23:59:59')
FROM #temp t
SELECT * FROM #temp
结果:
StartDate EndDate Month Year
2014-12-15 00:00:00.000 2015-01-25 23:59:59.000 12 2014
2015-01-26 00:00:00.000 2015-02-25 23:59:59.000 1 2015
2015-02-26 00:00:00.000 2015-03-25 23:59:59.000 2 2015
编辑:
如果你想从下一个StartDate计算EndDate,这是你的UPDATE语句:
UPDATE t
SET EndDate = (SELECT top 1 DateAdd(s, -1, StartDate) FROM #temp
WHERE t.StartDate < StartDate
ORDER BY startdate)
FROM #temp t
结果:
StartDate EndDate Month Year
2014-12-15 00:00:00.000 2015-01-25 23:59:59.000 12 2014
2015-01-26 00:00:00.000 2015-02-25 23:59:59.000 1 2015
2015-02-26 00:00:00.000 null 2 2015
答案 1 :(得分:0)
样本表
CREATE TABLE #TEMP(DATES DATETIME,DATES DATETIME,[MONTH] INT,[YEAR] INT)
INSERT INTO #TEMP
SELECT '2014-12-15 00:00:00', NULL, 12, 2014
UNION ALL
SELECT '2015-01-26 00:00:00', NULL, 1, 2015
UNION ALL
SELECT '2015-02-26 00:00:00', NULL, 2, 2015
<强> QUERY 强>
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY STARTDATE)RNO, STARTDATE
FROM #TEMP
)
,CTE2 AS
(
SELECT C1.STARTDATE,
ISNULL(DATEADD(S,-1,C2.STARTDATE),DATEADD(S,-1,DATEADD(MONTH,1,C1.STARTDATE))) ENDDATE
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1
)
UPDATE #TEMP
SET EndDate = CTE2.ENDDATE
FROM #TEMP T1
JOIN CTE2 ON T1.STARTDATE=CTE2.STARTDATE
<强> RESULT 强>
答案 2 :(得分:0)
您也可以使用OUTER APPLY
执行此操作select
c.StartDate
DATEADD(SECOND,-1,e.StartDate) EndDate
DATEPART(MONTH,StartDate) [Month],
DATEPART(YEAR,StartDate) [Year]
from [Cut-Off] c
outer apply (
select TOP 1
e.StartDate
from [Cut-Off] e
where
e.StartDate > c.StartDate
order by
e.StartDate
) e