How to add/subtract date/time components using a calculated interval? - teradata

I'd like to get this to work in Teradata:
Updated SQL for better example
select
case
when
current_date between
cast('03-10-2013' as date format 'mm-dd-yyyy') and
cast('11-03-2013' as date format 'mm-dd-yyyy')
then 4
else 5
end Offset,
(current_timestamp + interval Offset hour) GMT
However, I get an error of Expected something like a string or a Unicode character blah blah. It seems that you have to hardcode the interval like this:
select current_timestamp + interval '4' day
Yes, I know I hardcoded it in my first example, but that was only to demonstrate a calculated result.
If you must know, I am having to convert all dates and times in a few tables to GMT, but I have to account for daylight savings time. I am in Eastern, so I need to add 4 hours if the date is within the DST timeframe and add 5 hours otherwise.
I know I can just create separate update statements for each period and just change the value from a 4 to a 5 accordingly, but I want my query to be dynamic and smart.

Here's the solution:
select
case
when
current_date between
cast('03-10-2013' as date format 'mm-dd-yyyy') and
cast('11-03-2013' as date format 'mm-dd-yyyy')
then 4
else 5
end Offset,
(current_timestamp + cast(Offset as interval hour)) GMT
You have to actually cast the case statement's return value as an interval. I didn't even know interval types existed in Teradata. Thanks to this page for helping me along:
http://www.teradataforum.com/l081007a.htm

If I understand correctly, you want to multiply the interval by some number. Believe it or not, that's literally all you need to do:
select current_timestamp as right_now
, right_now + (interval '1' day) as same_time_tomorrow
, right_now + (2 * (interval '1' day)) as same_time_next_day
Intervals have always challenged me for some reason; I don't use them very often. But I've had this little example in my Teradata "cheat sheet" for quite a while.

Two remarks:
You could return an INTERVAL instead of an INT
The recommended way to write a date literal in Teradata is DATE 'YYYY-MM-DD' instead of CAST/FORMAT
select
case
when current_date between DATE '2013-03-10' and DATE '2013-11-03'
then interval '4' hour
else interval '5'hour
end AS Offset,
current_timestamp + Offset AS GMT

Related

SQLite strftime() weekday

I have been trying with no success to to count how many values were created in a specific week day:
SELECT count(*) as count FROM packets WHERE strftime("%w", timeIn) = '1';
I have this values in timeIn
1472434822.60033
1472434829.12632
1472434962.34593
I don't know what I am doing wrong here.
furthermore, if I use this:
SELECT count(*) as count FROM packets WHERE strftime("%w", timeIn) = '6';
I get
2
which makes no sense. Thank you in advance.
You appear to be storing the date as the number of seconds since 1970 (the Unix epoch) - a common representation. The time strings accepted by the SQLite date functions (see the Time Strings section) default to interpreting numeric time strings as a Julian day numbers:
Similarly, format 12 is shown with 10 significant digits, but the date/time functions will really accept as many or as few digits as are necessary to represent the Julian day number.
You can see this with the following SELECT:
SELECT strftime('%Y-%m-%d', 1472428800.6) AS t
the result of which is:
4026-48-26
For your date representation to be interpreted as a Unix epoch, you need to include 'unixepoch' in the strftime call:
SELECT strftime('%Y-%m-%d', 1472428800.6, 'unixepoch') AS t
which returns:
2016-08-29
If you modify your SELECT to be:
SELECT count(*) as count FROM packets WHERE strftime("%w", timeIn, 'unixepoch') = '6'
you should see results more inline with your expectations.

How do you update an existing date to a random date in a range?

In one of my tables I have datetime field in which the data in the table column is populated with something like "2016-01-07 01:33:00".
What I want to do is change ONLY the date to a random date within a range (ie: 2016-02-01 thru 2016-02-28) without changing the time. The end result might be "2016-02-13 01:33:00".
What mysql command string would accomplish this task?
Something like
UPDATE someTable SET someDate = DATE_ADD(
someDate,
INTERVAL
DATEDIFF(rangeStart, someDate) +
ROUND(RAND()*DATEDIFF(rangeEnd, rangeStart))
DAY
);
where someTable.someDate is your existing data, and rangeStart and rangeEnd are the boundaries of your target date range.
Here you take the initial date, add enough days to it to reach the range start, and then further add a random number of days no greater than the number of days in your target range.
In MsSQL it could be:
select dateadd(day,cast((RAND() * 30) as int),getdate())
Substitute getdate() with your input date.
(RAND() * 30) is used to randomly generate a number of days up to 30.

SQLite : obtain current week

I'm trying to obtain the current week for date comparison in SQLite.
I have no problem for last month, last year, today, yesterday... but don't find the solution to have the current week.
I tried lot of things like:
SELECT tastings.* FROM tastings
WHERE (DATE(tastings.date) > DATE('now','weekday 1','+ 7 days'))
Can you help me ? Thanks.
This code gives you the week number where the first day of week is monday. It also works well for last and first weeks of the year.
strftime('%W', 'now', 'localtime', 'weekday 0', '-6 days')
I guess you want compare 2 date, Assume you have a table named _testTbl and have 3 column _id INTEGER, _name TEXT, _recordDate TEXT
you want name that record this week
you can use below code:
SELECT * FROM _testTbl
WHERE _recordDate > datetime('now', 'start of day', 'weekday 6', '-7 day')
note that this week start by saturday (sunday 0, monday 1, ..., saturday 7)
this t-sql means:
datetime is a sqlite date and time function.
first parameter is given time: 'now' means the current time.
second parameter take the time to start of day.
third parameter take time to the next weekday number (in this case, saturday).
fourth parameter take time to start of week
What is stored inside the tastings.date column? Note that SQLite does not have “timestamp” type affinity, so probably you store Text (some representation of the date) or integer (julian day, epoch…)
All time and date functions expect a valid time string and convert that time string to another string format. If tastings.date contains a week number then use:
AND cast(tastings.date AS TEXT) = strftime('%W','now')
This helps me to compare the 2 dates using the week of the year.
AND ( strftime('%W', tastings.date) = strftime('%W', 'now') )
Thanks you.

Correct date range in SQL

This has gotten me a little paranoid, but I'm retrieving a set of records that fall within a period of time, say, the period from the january 1, 2011 (starting at midnight) to march 31, 2011 (all records up to 11:59:59 PM)
I'm using the condition
t.logtime between to_date('2011-01-01', 'yyyy-mm-dd') and to_date('2011-03-31')
Note that logtime is a datetime field.
Does this reflect what I want? Or am I actually missing 24 hours less a second?
I could specify the time as well, but I was hoping I this could be done without it.
Yes, you are missing nearly all of the last day. There are various solutions; probablt the simplest is:
t.logtime >= to_date('2011-01-01', 'yyyy-mm-dd')
and t.logtime < to_date('2011-04-01', 'yyyy-mm-dd')
I'd use the ANSI date literal syntax too:
t.logtime >= date '2011-01-01'
and t.logtime < date '2011-04-01'
Another way is:
trunc(t.logtime) between date '2011-01-01' and date '2011-03-31'
but note that that can no longer use an index on logtime (though it can use an index on trunc(logtime)).

DateAdd function in pl/sql

As the title suggested , I am looking for a function in pl /sql which does something similar like the DateAdd function.
I have been looking and I found the add_months function but I would really like one that is a little more variable since I need to be able to add minutes, hours , days etc.
It appears there's not many solutions :
PL/SQL allows you to perform arithmetic operations directly on date variables. You may add numbers to a date or subtract numbers from a date. To move a date one day in the future, simply add 1 to the date as shown below:
hire_date + 1
You can even add a fractional value to a date. For example, adding 1/24 to a date adds an hour to the time component of that value. Adding 1/(24*60) adds a single minute to the time component, and so on.
Besides adding numbers to dates - though it's the simplest way - you can add intervals like that:
date1 := date2 + interval '1' day;
date1 := date2 + interval '2' month;
date1 := date2 + interval '3' year;
It's almost the same but I prefer latter for better readability.

Resources