简体   繁体   中英

Teradata date time subtraction and conversion

How can I convert the following Oracle conversion to Teradata:

select
round((current_timestamp - ah.adate) - (ah.ahdate-ah.adate),1) 
,round(ah.ahdate-ah.addate,1) 
from actions ah

I believe one of the follow comparisons should work in Teradata:

SELECT Current_Timestamp - CAST(ah.addate AS TimeStamp(6)) DAY (4) TO SECOND(4) AS TimeInterval
     , Current_Date - CAST(ah.addate AS DATE) DAY(4) AS DayInterval /* May Not be necessary as two dates can be subtracted/added without INTERVAL */
     , Current_Date - ah.addate AS DayDifference /* If AdDate is a DATE in Teradata */
FROM actions ah

EDIT : Break down difference to seconds between timestamps and then use math to calculate days between two timestamps as FLOAT.

SELECT (((EXTRACT (DAY FROM (Current_Timestamp - Timestamp '2015-04-01 21:13:40' DAY TO SECOND)) * 86400)
    + (EXTRACT (HOUR FROM (Current_Timestamp - Timestamp '2015-04-01 21:13:40' DAY TO SECOND)) * 3600)
    + (EXTRACT (MINUTE FROM (Current_Timestamp - Timestamp '2015-04-01 21:13:40' DAY TO SECOND)) * 60)
    + (EXTRACT (SECOND FROM (Current_Timestamp - Timestamp '2015-04-01 21:13:40' DAY TO SECOND))) AS FLOAT)) / 86400.00

This is ugly as sin, but it will get you number of days to a single decimal place from the subtraction of two intervals.

SELECT 
    ROUND(
        STRTOK(CAST((TIMESTAMP '2017-04-17 07:08:34.000'  - TIMESTAMP '2015-04-09 16:30:14.000' DAY(4) TO HOUR) AS VARCHAR(10)),' ',1) + 
        (STRTOK(CAST((TIMESTAMP '2017-04-17 07:08:34.000'  - TIMESTAMP '2015-04-09 16:30:14.000' DAY(4) TO HOUR) AS VARCHAR(10)),' ',2)/24)
        ,1)

The tricky part here is that when you subtract two TIMESTAMPs , what you end up with is an INTERVAL data type. We convert that interval data type to HOUR , then cast the results as a VARCHAR , which in this example looks like 738 15 . That's 738 days and 15 hours.

Using STRTOK() , we can pick out the days (the first token) and then add in the number of hours (second token) divided by 24.

The result is then rounded.

Perhaps there is a less involved way, but I haven't discovered it yet.

使用此解决方案:,trim(abs((CAST(ah.ahdate AS DATE)-CAST(ah.adate AS DATE))))),(cast(trim(abs((EXTRACT(HOUR FROM ah.ahdate))-abs (EXTRACT(HOUR FROM ah.adate))))作为varchar(10)))/ 24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM