gpt4 book ai didi

sql - 在sql中获取两个日期之间的月数和天数之间的差异

转载 作者:行者123 更新时间:2023-12-03 22:23:52 25 4
gpt4 key购买 nike

我需要得到两个日期之间的差异,如果差异是 84 天,我可能应该输出 2 个月零 14 天,我刚刚给出的代码给出了总数。这是代码

SELECT Months_between(To_date('20120325', 'YYYYMMDD'),
To_date('20120101', 'YYYYMMDD'))
num_months,
( To_date('20120325', 'YYYYMMDD') - To_date('20120101', 'YYYYMMDD') )
diff_in_days
FROM dual;

输出是:
NUM_MONTHS    DIFF_IN_DAYS
2.774193548 84

例如,我需要此查询的输出最差为 2 个月和 14 天,否则我不介意我是否可以在月份数字之后获得确切的天数,因为那些天数并不是真正的 14 天,因为所有月份都没有30天。

最佳答案

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 union all
select trunc(sysdate-1) dt1, sysdate from dual
) sample_data

结果:
|                        DT1 |                       DT2 | MTHS |     DAYS |
----------------------------------------------------------------------------
| January, 01 2012 00:00:00 | March, 25 2012 00:00:00 | 2 | 24 |
| January, 01 2012 00:00:00 | January, 01 2013 00:00:00 | 12 | 0 |
| January, 01 2012 00:00:00 | January, 01 2012 00:00:00 | 0 | 0 |
| February, 28 2012 00:00:00 | March, 01 2012 00:00:00 | 0 | 2 |
| February, 28 2013 00:00:00 | March, 01 2013 00:00:00 | 0 | 1 |
| February, 28 2013 00:00:00 | April, 01 2013 00:00:00 | 1 | 1 |
| August, 14 2013 00:00:00 | August, 15 2013 05:47:26 | 0 | 1.241273 |

测试链接: SQLFiddle

关于sql - 在sql中获取两个日期之间的月数和天数之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11500098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com