Академический Документы
Профессиональный Документы
Культура Документы
Dates, times, and timestamps in Teradata (V2R4.1) can be a little tricky. This d
ocument explains how to do various things that you may want to do.
Preliminaries
The examples below use Teradata syntax, so they assume that you are running in B
TEQ. If you are using Queryman, be sure to uncheck the option box "Allow use of
ODBC SQL Extensions in queries".
datecol means a column defined as DATE.
Dates
/*** Last day of the month is still the last day ***/
select add_months(date '2002-01-31', 1);
ADD_MONTHS(2002-01-31, 1)
-------------------------
2002-02-28
Special calendars
Your business may have special requirements, such as a retail calendar that is a
lways a multiple of weeks. Such data must be stored in a table and joined to in
your queries.
Times
Time differences
First we shall address the case where your time data is defined as a number (FLO
AT or DECIMAL, perhaps) in hhmmss form <;
select ((time02 / 10000) * 3600 +
(time02 / 100 MOD 100) * 60 +
(time02 MOD 100)) -
((time01 / 10000) * 3600 +
(time01 / 100 MOD 100) * 60 +
(time01 MOD 100)) as time_diff
from dttest2;
time_diff
-------------
6432. [in seconds -- about 1.8 hours]
If the earlier time could fall on one day and the later time on the next day, yo
u may have to add 86,400 (the number of seconds in one day) to the later time, l
ike so:
select case
when time02 >= time01 then
((time02 / 10000) * 3600 +
(time02 / 100 MOD 100) * 60 +
(time02 MOD 100)) -
((time01 / 10000) * 3600 +
(time01 / 100 MOD 100) * 60 +
(time01 MOD 100))
else /*** Midnight has passed ***/
(((time02 / 10000) * 3600 +
(time02 / 100 MOD 100) * 60 +
(time02 MOD 100)) + 86400) -
((time01 / 10000) * 3600 +
(time01 / 100 MOD 100) * 60 +
(time01 MOD 100))
end as time_diff
from dttest2;
time_diff
-------------
18094.
Next we consider the case where your time data is defined as TIME(n). The usual
way to take the difference of two times would be as follows:
select time02 - time01 hour(2) to second
from dttest3;
(time02 - time01) HOUR TO SECOND
--------------------------------
5:02:40.000000
The above result has a data type of INTERVAL. If, however, you want to compute t
he difference in seconds, as above, you again have to split the times up:
select (extract(hour from time02) * 3600 +
extract(minute from time02) * 60 +
extract(second from time02)) -
(extract(hour from time01) * 3600 +
extract(minute from time01) * 60 +
extract(second from time01)) as time_diff
from dttest3;
time_diff
-----------
18160
Timestamps
You can also convert this interval to seconds or minutes like so:
/*** Difference in seconds ***/
select (ts01 - ts04 day(4) to second) as tsdiff,
(extract(day from tsdiff) * 86400)
+ (extract(hour from tsdiff) * 3600)
+ (extract(minute from tsdiff) * 60)
+ extract(second from tsdiff) as sec_diff
from dttest;
tsdiff sec_diff
------------------ --------------
2 07:11:24.000000 198684.000000