如何计算 db2 中两个日期列之间的天数?我如何更正此查询中的天数差异?

How to calculate days between two date columns in db2?? how do i correct the difference of days in this query?

我的查询:

SELECT CD1
, OD1
,CHAR(DATE(SUBSTR(CHAR(CD1),1,4) ||'-'||
    SUBSTR(CHAR(CD1),5,2) ||'-'||
   SUBSTR(CHAR(CD1),7,2)), USA)
AS "CDate_Conversion"
,CHAR(DATE(SUBSTR(CHAR(OD1),1,4) ||'-'||
    SUBSTR(CHAR(OD1),5,2) ||'-'||
   SUBSTR(CHAR(OD1),7,2)), USA)
AS "OConv"

, CD1-OD1 AS Days

FROM PDAT.ZPKD

输出:

Crt Date Date Ordered CDate_Conversion OConv    DAYS
20171201    20171130    12/01/2017  11/30/2017  71
20171003    20170929    10/03/2017  09/29/2017  74
20171009    20170908    10/09/2017  09/08/2017  101
20171009    20170921    10/09/2017  09/21/2017  88
20171002    20170929    10/02/2017  09/29/2017  73
20171009    20171006    10/09/2017  10/06/2017  3
20181010    20181010    10/10/2018  10/10/2018  0
20180723    20180723    07/23/2018  07/23/2018  0
20180710    20180709    07/10/2018  07/09/2018  1
20181010    20181009    10/10/2018  10/09/2018  1
20180831    20180830    08/31/2018  08/30/2018  1
20180827    20180814    08/27/2018  08/14/2018  13
20180828    20180827    08/28/2018  08/27/2018  1
20180403    20180403    04/03/2018  04/03/2018  0
20180405    20180403    04/05/2018  04/03/2018  2
20180820    20180820    08/20/2018  08/20/2018  0
20180920    20180919    09/20/2018  09/19/2018  1
20180305    20180305    03/05/2018  03/05/2018  0
20180306    20180305    03/06/2018  03/05/2018  1

前 5 行的天数差异不正确。

另外,我不确定如何找到转换后的列的天数差异,所以我选择了 CTD-OTD!

OTD 没有时间列,所以不能使用 TIMESTAMPDIFF。

注意:我随机选择了天数差异错误的行来显示这里的resuly=ts。

你很接近。使用 DAYS() 函数为每个日期计算一个整数,然后减去它们。

查询应如下所示:

SELECT CD1
, OD1
,CHAR(DATE(SUBSTR(CHAR(CD1),1,4) ||'-'||
    SUBSTR(CHAR(CD1),5,2) ||'-'||
   SUBSTR(CHAR(CD1),7,2)), USA)
AS "CDate_Conversion"
,CHAR(DATE(SUBSTR(CHAR(OD1),1,4) ||'-'||
    SUBSTR(CHAR(OD1),5,2) ||'-'||
   SUBSTR(CHAR(OD1),7,2)), USA)
AS "OConv",

( DAYS(DATE(
    SUBSTR(CHAR(CD1),1,4) ||'-'||
    SUBSTR(CHAR(CD1),5,2) ||'-'||
    SUBSTR(CHAR(CD1),7,2)), USA)
 -
  DAYS(DATE(
    SUBSTR(CHAR(OD1),1,4) ||'-'||
    SUBSTR(CHAR(OD1),5,2) ||'-'||
    SUBSTR(CHAR(OD1),7,2)), USA)
) AS Days

FROM PDAT.ZPKD

@Aryana 这样写可读性更好:

SELECT (Days(TO_DATE(Char(CD1), 'YYYYMMDD')) -
        Days(TO_DATE(Char(OD1), 'YYYYMMDD')) ) AS Days
FROM PDAT.ZPKD  

TO_DATE是一个非常强大的功能。