我有两个日期开始日期和结束日期。 我怎么知道这两个日期之间是否有01/01意味着新的一年。
例如:
Table test
id start date End date
1 02/03/2013 19/09/2016
2 15/02/2015 30/06/2015
输出
id start date End date
1 02/03/2013 31/12/2013
1 01/01/2014 31/12/2014
1 01/01/2015 31/12/2015
1 01/01/2016 19/09/2016
2 15/02/2015 30/06/2015
如何做到这一点?
答案 0 :(得分:1)
您会知道年组件是否不同:
select t.*,
(case when year(startdate) < year(enddate) then 1
else 0
end) as HasNewYear
from table t;
答案 1 :(得分:0)
您可以使用递归CTE查找两个日期之间的所有年份,然后将日期转换为DATETIME
个对象以获得所需的输出:
;WITH CTE AS (
SELECT ID, DATEPART(YEAR, STARTDATE) AS YR, ENDDATE
FROM TABLE1
UNION ALL
SELECT ID, YR+1, ENDDATE
FROM CTE
WHERE YR < DATEPART(YEAR,ENDDATE))
SELECT A.ID, CASE WHEN CAST(A.YR AS VARCHAR)+'-01-01' > B.STARTDATE THEN CAST(A.YR AS VARCHAR)+'-01-01' ELSE B.STARTDATE END AS STARTDATE, CASE WHEN CAST(A.YR AS VARCHAR)+'-12-31' < B.ENDDATE THEN CAST(A.YR AS VARCHAR)+'-12-31' ELSE B.ENDDATE END AS ENDDATE
FROM CTE AS A
JOIN TABLE1 AS B
ON A.ID=B.ID
ORDER BY A.ID