SQL 获取两个日期之间的确切日期差

问题描述 投票:0回答:1

我需要计算两个日期之间的精确差异

例如,date1= '2011-06-27' 和 date2= '2013-06-27' 之间的差异应返回 24 个月,而 date1= '2011-06-27' 和 date2= '2013-06-29 ' 应返回 24 个月零 2 天。

我尝试了以下逻辑,将差值转换为天数并除以 30,但这给出了错误,因为所有月份除以 30 是不正确的。有没有办法在 SQL 中实现这一点

-- Sample table T1 with Date1 and Date2 columns
CREATE TABLE T1 (
    Date1 DATE,
    Date2 DATE
);

-- Insert your actual data
INSERT INTO T1 (Date1, Date2) VALUES ('2011-06-27', '2013-06-27');

-- Calculate the difference in days and convert to months with a fraction
SELECT 
    Date1,
    Date2,
    DATEDIFF(DAY, Date1, Date2) AS DaysDifference,
    CAST(DATEDIFF(DAY, Date1, Date2) / 30.0 AS DECIMAL(10, 2)) AS MonthsWithFraction
FROM T1;
sql sap-iq
1个回答
0
投票

您需要计算跨越一个月边界的次数,然后添加剩余的天数。

这是为 SQL Server 编写的,但应该类似。

-- Sample table T1 with Date1 and Date2 columns
CREATE TABLE T1 (
    Date1 DATE,
    Date2 DATE
);

-- Insert your actual data
INSERT INTO T1 (Date1, Date2)
VALUES ('2011-06-27', '2013-06-27')
  , ('2011-06-27', '2013-06-29');

with 
a as (
  select 
    date1
  , date2
  , datediff(month, date1, date2) as DiffMo
  from T1
),
b as (
  select
    date1
  , date2
  , DiffMo
  , datediff(day, dateadd(month, DiffMo, date1), date2) as AdditionalDays
  from a
)

select 
  date1
, date2
, cast(DiffMo as varchar(5)) + ' months ' + cast(AdditionalDays as varchar(5)) + ' days' as DateDiff
from b

https://dbfiddle.uk/-CwpLKQf

© www.soinside.com 2019 - 2024. All rights reserved.