想用SQL查询两个日期之间的周年数,例如:
2005.1.5至2006.1.4之间,显示是0年
2005.1.5至2006.1.5之间,显示是1年
2005.1.5至2015.1.3号之间,显示是9年
2005.1.5至2015.1.4号之间,显示是10年
请教 高手这个SQL该怎样写,谢谢
------解决思路----------------------
WITH table1(dt1,dt2) AS (
SELECT Convert(datetime,'2005-01-05',120),Convert(datetime,'2006-01-04',120) UNION ALL
SELECT '2005-01-05','2006-01-05' UNION ALL
SELECT '2005-01-05','2015-01-03' UNION ALL
SELECT '2005-01-05','2015-01-05'
)
SELECT *,
DateDiff(year,dt1,dt2)+
CASE WHEN Convert(varchar(5),dt1,10) <= Convert(varchar(5),dt2,10)
THEN 0
ELSE -1
END 周年
FROM table1
dt1 dt2 周年
----------------------- ----------------------- -----------
2005-01-05 00:00:00.000 2006-01-04 00:00:00.000 0
2005-01-05 00:00:00.000 2006-01-05 00:00:00.000 1
2005-01-05 00:00:00.000 2015-01-03 00:00:00.000 9
2005-01-05 00:00:00.000 2015-01-05 00:00:00.000 10
------解决思路----------------------
SELECT DATEDIFF(YEAR
,CONVERT(VARCHAR(4),StartDate,112)+'.1.1'
,DATEADD(DAY,-DATEDIFF(DAY,CONVERT(VARCHAR(4),StartDate,112)+'.1.1',StartDate),EndDate)
)周年数
FROM TB
------解决思路----------------------
declare @i datetime,@j datetime
set @i='2005-1-5'
set @j='2006-1-4'
select DATEDIFF(year,@i,@j)-
case when convert(varchar(5),@i,110)>convert(varchar(5),@j,110)
then 1 else 0 end