我需要找到两个日期之间的差异,根据结果进行一些计算。
让我们说列start_date
的值为1 / Jan / 2014,列end_date
的值为15 / Mar / 2014。我想要的结果是以下格式:
months | days_remain |
----------------------
2 15
我可以使用MONTH
函数分别找到DAY
差异和TIMESTAMPDIFF
之间的差异(2个月和74天)。但如何找出剩余的15天?
答案 0 :(得分:0)
我认为这可能就是你想要的。然而,它确实会剩下14天,但正如Jaugar Chang在评论中指出的那样,如果3月1日到3月15日之间的差异是14天那么应该是正确的。
select
timestampdiff(
month,
start_date,
end_date
) as months,
datediff(
end_date,
timestampadd(
month,
timestampdiff(
month,
start_date,
end_date
)
,start_date
)
) as days_remain
from test;
示例结果:
| START_DATE | END_DATE | MONTHS | DAYS_REMAIN |
|------------------|----------------|--------|-------------|
| January, 01 2014 | March, 15 2014 | 2 | 14 |
| January, 10 2014 | March, 13 2014 | 2 | 3 |
答案 1 :(得分:0)
您可以使用DATEDIFF查看2个日期之间的差异
SELECT DATEDIFF('2006-04-01','2005-04-01');
答案 2 :(得分:0)
试试这个,我希望它能为你效劳。
select DateDiff(d, datepart(month,[Start_Date]),datepart(month,End_Date)) as Months,
(30-day(end_date)) as Days_remain
from Sdate
答案 3 :(得分:0)
这肯定会有效。
Declare @StartDate datetime
Declare @EndDate datetime
Declare @years varchar(40)
Declare @months varchar(30)
Declare @days varchar(30)
set @StartDate ='2014/01/01'
set @EndDate = '2014/03/15'
select @years=datediff(year,@StartDate,@EndDate)
select @months=datediff(month,@StartDate,@EndDate)-(datediff(year,@StartDate,@EndDate)*12)
select @days=datepart(d,@EndDate)-datepart(d,@StartDate)
select @years +' years, ' +@months +' months, '+@days +' days' asYearMonthDay
答案 4 :(得分:0)
试试这个。请参阅示例数据:
select
dt1, dt2,
trunc( months_between(dt2,dt1) ) mths,
dt2 - add_months( dt1, trunc(months_between(dt2,dt1)) ) days
from
(
select date '2012-01-01' dt1, date '2012-03-25' dt2 from dual union all
select date '2012-01-01' dt1, date '2013-01-01' dt2 from dual union all
select date '2012-01-01' dt1, date '2012-01-01' dt2 from dual union all
select date '2012-02-28' dt1, date '2012-03-01' dt2 from dual union all
select date '2013-02-28' dt1, date '2013-03-01' dt2 from dual union all
select date '2013-02-28' dt1, date '2013-04-01' dt2 from dual
) sample_data;
希望它有所帮助。