How to get correct year, month and day in firebird function datediff

前端 未结 2 1713
粉色の甜心
粉色の甜心 2021-01-25 01:31

I have to ask another question about datediff in Firebird. I don`t know how to get correct result in this case: worker x has two contract of employment, first in the period 1988

2条回答
  •  抹茶落季
    2021-01-25 01:58

    You should sum days first then sum the result and then calculate Y, M, D

    SELECT
    KP3.id_contact 
    , (KP3.D2-KP3.D1) / (12*31) AS Y
    , ((KP3.D2-KP3.D1) - ((KP3.D2-KP3.D1) / (12*31)) * 12 * 31) / 31 AS M
    , CAST(MOD((KP3.D2-KP3.D1) - (((KP3.D2-KP3.D1) / (12*31)) * 12 * 31), 31) AS INTEGER) AS D
    FROM
    (SELECT
    KP2.id_contact, SUM(KP2.D1) AS D1, SUM(KP2.D2) AS D2
    FROM
        (
        SELECT
        KP.id_contact, DATEDIFF(MONTH, KP.DATE_FROM, KP.DATE_TO) / 12 AS Y, CAST(MOD(DATEDIFF(MONTH, KP.DATE_FROM, KP.DATE_TO), 12) AS INTEGER) AS M 
        , EXTRACT(YEAR FROM KP.DATE_FROM)*12*31+EXTRACT(MONTH FROM KP.DATE_FROM)*31+EXTRACT(DAY FROM KP.DATE_FROM) D1
        , EXTRACT(YEAR FROM KP.DATE_TO)*12*31+EXTRACT(MONTH FROM KP.DATE_TO)*31+EXTRACT(DAY FROM KP.DATE_TO) D2 
        FROM
        KP  
        ) AS KP2
    GROUP BY KP2.id_contact
    ) AS KP3
    

提交回复
热议问题