0

我需要找到两个日期之间的差异,以便根据结果进行一些计算。

假设 columnstart_date的值为 1/Jan/2014 和 columnend_date的值为 15/Mar/2014。我想要的结果是以下格式:

months | days_remain |
----------------------
   2          15

我可以使用函数分别(如 2 个月和 74 天)找到MONTH差异和DAY差异。TIMESTAMPDIFF但是如何找出剩余的 15 天呢?

4

5 回答 5

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;

示例 SQL 小提琴

样本结果:

|       START_DATE |       END_DATE | MONTHS | DAYS_REMAIN |
|------------------|----------------|--------|-------------|
| January, 01 2014 | March, 15 2014 |      2 |          14 |
| January, 10 2014 | March, 13 2014 |      2 |           3 |
于 2014-11-10T10:31:59.353 回答
0

您可以使用 DATEDIFF 查看 2 个日期之间的差异

SELECT DATEDIFF('2006-04-01','2005-04-01');

http://lists.mysql.com/mysql/196414

于 2014-11-10T10:32:42.303 回答
0

试试这个,我希望它对你有用。

select DateDiff(d, datepart(month,[Start_Date]),datepart(month,End_Date)) as  Months,

(30-day(end_date)) as Days_remain

from Sdate 
于 2014-11-10T10:41:28.263 回答
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 
于 2014-11-10T11:19:22.327 回答
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;

希望能帮助到你。

于 2014-11-10T11:31:01.693 回答