db2 如何在as400中以YYYYMMDD格式提取两个日期之间的月份

7lrncoxx  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(180)

我有一个400数据库,其中有两个日期,都是YYYYMMDD格式。
我想把这两个日期之间的几个月去掉
以下是我的查询

SELECT MONTH(TO_DATE) - MONTH(FROM_DATE) as Months
FROM GREY  WHERE ID='1234'

这会将Months返回为0
其中YEAR(TO_DATE)- YEAR(FROM_DATE)是有效的。
我的输入是TO_DATE - 20160712 ; FROM_DATE - 20140728 .预期24个月作为答复

dced5bon

dced5bon1#

您可以使用MONTHS_BETWEENCEIL的组合

with grey (id,TO_DATE,FROM_DATE) as (values ('1234','2016-07-12','2014-07-28'))
SELECT
  CEIL(MONTHS_BETWEEN(TO_DATE,FROM_DATE)) as Months
FROM GREY
WHERE ID='1234'
toe95027

toe950272#

另一个选项是TIMESTAMPDIFF()

with grey (id,TO_DATE,FROM_DATE) as (values ('1234',date('2016-07-12'),date('2014-07-28')))
SELECT
  timestampdiff(64, cast(timestamp(TO_DATE) - timestamp(FROM_DATE) as char(22))) as Months
FROM GREY
WHERE ID='1234';

但是请注意,timestampdiff()规则意味着上面的返回值是23,而不是您想要的24。因为开始日期是该月的28号,结束日期是12号。
您可以通过添加LAST_DAY()来获得所需的结果

with grey (id,TO_DATE,FROM_DATE) as (values ('1234',date('2016-07-12'),date('2014-07-28')))
SELECT
  timestampdiff(64, cast(timestamp(last_day(TO_DATE)) - timestamp(last_day(FROM_DATE)) as char(22))) as Months
FROM GREY
WHERE ID='1234';

相关问题