Given a table like this:
cust_id time
123 2015-01-01 12:15:05
123 2015-01-01 12:17:06
123 2015-01-02 13:15:08
123 2015-01-02 1
There's no LAG
in Teradata, but you can rewrite it:
SELECT
t.*
, (time)
- min(time)
OVER (PARTITION BY cust_id
ORDER BY time
ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) SECOND(4)
FROM
table_01 as t
When you try to get seconds you will encouter "Interval Overflow" errors, i.e. more than 9999 seconds. Either change to DAY(4) TO SECOND
or use this SQL UDF I wrote a few years ago for calculating the difference of two timestamps in seconds:
REPLACE FUNCTION TimeStamp_Diff_Seconds
(
ts1 TIMESTAMP(6)
,ts2 TIMESTAMP(6)
)
RETURNS DECIMAL(18,6)
LANGUAGE SQL
CONTAINS SQL
RETURNS NULL ON NULL INPUT
DETERMINISTIC
SQL SECURITY DEFINER
COLLATION INVOKER
INLINE TYPE 1
RETURN
(CAST((CAST(ts2 AS DATE)- CAST(ts1 AS DATE)) AS DECIMAL(18,6)) * 60*60*24)
+ ((EXTRACT( HOUR FROM ts2) - EXTRACT( HOUR FROM ts1)) * 60*60)
+ ((EXTRACT(MINUTE FROM ts2) - EXTRACT(MINUTE FROM ts1)) * 60)
+ (EXTRACT(SECOND FROM ts2) - EXTRACT(SECOND FROM ts1))
;