Subtracting and changing datetime in Teradata - datetime

My Col_1 looks like this-
1/20/2015 11:12:00.000000
1/21/2015 13:00:00.000000
... and so on.
I want to do (row 2 -row 1) and display the result as 1572 minutes.
Also, can someone tell me how to simply change the format of this cell to
mm/dd/yy hh:mm:ss
and get rid of all the decimals?

This should get you thinking in the right direction. The ORDER BY of the window function may need to be another column on your table if you don't want the window ordered by the actual column you are trying to do the time arithmetic. If you can share more details about the table or take a stab at the SQL yourself, we might be able to arrive at a better solution.
SELECT (MIN(Col_1)
OVER(PARTITION BY 1 ORDER BY Col_1
ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) -
Col_1) MINUTE(4) AS MinutesElapsed
FROM MyTable;
Using the raw data you have given as a sample:
SELECT (TIMESTAMP '2015-01-21 13:00:00.00000' -
TIMESTAMP '2015-01-20 11:12:00.00000') MINUTE(4) AS MinutesElapsed;
As for the decimals:
SELECT CAST(Col_1 AS TIMESTAMP(0)) AS NewTimeStamp;

Related

Is there a way of looking up a datetime in a datetime reference table and returning corresponding data

Have been searching for the answer to this for a which but with no joy. Hoping you DAX geniuses can help out!
I have a table of transactional data with a date time column (in the format "dd/mm/yyyy hh:mm:ss")
I want to look this datetime up in a separate 'shift reference' table to add a new column to my transactional data i.e. if it falls between 2 date times (which it always will), Start time and End Time there will be a corresponding shift associated with it.
The format of this table is
Start time - End Time - Shift Pattern
In this table we have the datetime (in the same format as before) the shift started - "Start_Time", when it ended - "End_Time" and what 'Shift' was working. I want to use my transactional datetime to look up what shift was on when the transaction took place.
Ive tried combinations of Lookupvalue/Calculate/Max and on some occasions it has returned values, but never correct ones!
I hope this makes sense!
Best Regards,
Colin
You can use this code to add a calculated column with the Shift value looked up based on transaction timestamp.
Shift = CALCULATE (
VALUES ( Shift[SHIFT_PATTERN] ),
FILTER (
Shift,
Shift[start_time] <= [Timestamp] && Shift[end_time] > [Timestamp]
)
)
Just for showing another option, it is even possible to calculate transaction facts sliced by Shift without adding a column in the fact table. You may handle it in measures like below.
Transaction Count =
SUMX (
Shift,
COUNTROWS (
FILTER (
'Transaction',
'Transaction'[Timestamp] >= Shift[start_time]
&& 'Transaction'[Timestamp] < Shift[end_time]
)
)
)

How to calculate time differences HH:MM in a table?

Im working on a flight-logbook in sqlite.
The "flights"-table has the following structure:
CREATE TABLE flights (event_id INT PRIMARY KEY, date TEXT, offblock TEXT, onblock TEXT, duration TEXT;
My goal is to find a statement that i can insert into the "duration" column, so that I will have the flight duration there.
INSERT INTO flights VALUES (1, "2019-04-04", "12:00", "18:00", XXX);
The result of duration should be 06:00, like this:
SELECT duration from flights WHERE event_id = 1;
06:00
Can anyone give me a working hint how to do this in the easiest possible way?
Thanks a lot!
You can do it with strftime() and time() like this:
SELECT strftime('%H:%M', time(strftime('%s','18:00') - strftime('%s','12:00'), 'unixepoch'))
which results in:
06:00
What you want to do is pretty complex as you have a string which represents time, which there isn't an explicit type for in sqlite. It's quite complicated, but it is possible and you could do the following:
-First remove the colon from the string: how to remove characters from a string in sqlite3 database?
-Then convert this string to an int: Convert string to int inside WHERE clause of SQLITE statment
-You would need to do this for the hours and minutes separately, as ints are obviously 10 based and minutes are 60 based so you can't simply subtract them. You would do this via ths Substr(X,Y,Z) function: https://www.sqlite.org/lang_corefunc.html
-Then you would do arithmetic to subtract final - initial time for both the hours and minutes. https://www.w3resource.com/sqlite/arithmetic-operators.php
-Finally take the calculated hours, and minutes, and add a colon in between them (assuming you want the same format).
Like I said, it's kinda heavy.. but it is doable if this automation saves time in the long run. This should be enough to get you there.

How to Query for Recent Rows in SQLITE3

I'm using SQLite3 and trying to query for recent rows. So I'm having SQLite3 insert a unix timestamp into each row with strftime('%s','now'). My Table looks like this:
CREATE TABLE test(id INTEGER PRIMARY KEY, time);
INSERT INTO test (time) VALUES (strftime('%s','now')); --Repeated
SELECT * FROM test;
1|1516816522
2|1516816634
3|1516816646 --etc lots of rows
Now I want to query for only recent entries, for example, I'm trying to get all rows with a time within the last hour. I'm trying the following SQL query:
SELECT * FROM test WHERE time > strftime('%s','now')-60*60;
However, that always returns all rows regardless of the value in the time column. I really don't know what's going on.
Also, if I put WHERE time > strftime('%s','now') it'll return nothing (which is expected) but if I put WHERE time > strftime('%s','now')-1 then it'll return everything. I don't know why.
Here's one more example:
sqlite> SELECT , strftime('%s','now')-1 AS window FROM test WHERE time > window;
1|1516816522|1516817482
2|1516816634|1516817482
3|1516816646|1516817482
It seems that SQLite3 thinks the values in the middle column are greater than the values in the right column!?
This isn't at all what I expect. Can someone please tell me what's going on? Thanks!
The purpose of strftime() is to format values, so it returns a string.
When you try to do computations with its return value, the database must convert it into a number. And numbers and strings cannot be compared directly with each other.
You must ensure that both values in a comparison have the same data type.
The best way to do this is to store numbers in the table:
INSERT INTO test (time)
VALUES (CAST(strftime('%s','now') AS MAKE_THIS_A_NUMBER_PLEASE));
(Or just declare the column type as something with numeric affinity.)

How to find the nth largest value of each row in SQL

I have researched this problem and have found the answer for a single query, where you can find the nth value of a single column by using DESC OFFSET 2. What I am trying to do is find the nth value for each item in a row. For example, I'm working with a data base concerning bike share data. The data base stores the duration of each trip and the date. I'm trying to find the 3rd longest duration for each day in a data base. If I was going to find the max duration I would use the following code.
SELECT DATE(start_date) trip_date, MAX(duration)
FROM trips
GROUP BY 1
I want the output to be something like this.
Date 3rd_duration
1/1/2017 334
1/2/2017 587
etc
If the value of the third longest duration is the same for two or more different trips, I would like the trip with the lowest trip_id to be ranked 3rd.
I'm working in SQLite.
Any help would be appreciated.
Neither SQLite nor MySQL have a ROW_NUMBER function built in, so get ready for an ugly query. We can still group by the date, but to find the max duration we can use a correlated subquery.
SELECT
DATE(t1.start_date) AS start_date,
t1.duration
FROM trips t1
WHERE
(SELECT COUNT(*) FROM trips t2
WHERE DATE(t2.start_date) = DATE(t1.start_date) AND
t2.duration <= t1.duration) = 3;
Note that this approach might break down if you could have, for a given date, more than one record with the same duration. In this case, you might get multiple results, neither of which might actually be the third highest duration. In order to handle such ties, you should tell us what the logic is with regard to ties.
Demo here:
Rextester

Delete old records

I have a column in my sqlite table which is string and has the following format
2011-09-06 18:34:55.863414
You can see that it identifies date and time. I'd like to construct a query that will
delete all records that are older than certain date and time.
Is this possible?
Since your date is already in the best format (largest time-period values to smallest)
DELETE FROM myTable
WHERE myDateField < '2011-09-06 18:34:55.863414'
BTW -- dates are strings in sqllite, AFAIK (which is why the format matters -- biggest values to smallest, so it works alphabetically too). IF you want to treat them as dates, you can use functions. Some good examples here: http://sqlite.org/lang_datefunc.html
DELETE FROM tablename WHERE columnname < '2011-09-06 18:34:55.863414'
See:
http://www.sqlite.org/lang_datefunc.html

Resources