Can I add this format in sqlite3 - sql

I have a columns called time_spent and it is like: hh:mm:ss. For example, 00:23:11, this means it is 23 minutes and 11 seconds. I wonder how I can add up a multiple of these. Say like 00:23:11 + 00:10:20 = 00:33:31. I am not sure how to directly do that in commands. I have tried convert and CAST, but they ended up failed. Any help would be appreciated.

You can turn your times to seconds using time_to_sec(), sum them, and then turn the result to a time using sec_to_time().
As an example, the following query would compute the total time_spent over the whole table:
select sec_to_time(sum(time_to_sec(time_spent))) total_time_spent
from mytable
This will work even it your times are stored as string, since their format complies to MySQL format for the time datatype.
Note that MySQL time datatype can handle values between '-838:59:59' to '838:59:59' only. If your total time is greater than that, then you will not be able to convert it back to a time.

Once you store dates in DATE, TIME and DATETIME formats there are a multitude of available date and time functions you can use.

You can do it with the function time():
select time('00:23:11', '+00:10:20')
or just:
select time('00:23:11', '00:10:20')
Result:
00:33:31
If the sum may exceed 24 hours, for example when you want to add '23:59:59' to '00:23:11' then use this statement:
select
case
when strftime('%d', datetime('00:23:11', '23:59:59')) = '01' then time('00:23:11', '23:59:59')
else (24 + time('00:23:11', '23:59:59')) || strftime(':%M:%S', time('00:23:11', '23:59:59'))
end
Or:
select
(24 * (strftime('%d', datetime('00:23:11', '23:59:59')) - 1) + time('00:23:11', '23:59:59')) ||
strftime(':%M:%S', time('00:23:11', '23:59:59'))
Result:
24:23:10

Related

Finding Average Time Length in SQL

I am a beginner in SQL and I am using Big Query. I am looking to find the average length of time.
My columns are in the image.
Can someone please tell me how to write a query to find the average time for the column ride_length in minutes? The ride_length column is in h:mm format.
You will need something like this:
SELECT AVG(
CAST( SPLIT( ride_length, ':' )[OFFSET(1)] AS NUMERIC )
+ CAST( SPLIT( ride_length, ':' )[OFFSET(0)] AS NUMERIC ) * 60
)
FROM TheTable
SPLIT is used to separate hours from minutes and then each result converted (CAST) to NUMBER.
[I did not test it]
Here is the data verification query (untested as well) to check on format consistency:
SELECT
ride_id,
ride_length
WHERE NOT REGEXP_CONTAINS(ride_length, r'^(\d+\:\d+)$)';

SQL Server Converting Decimal into Time hh:mm, I need the total hours

I need to be able to get the total hours and minutes if it is over 24 hours from a decimal column in SQL Server.
This is the code I am using:
CAST(CAST(DATEADD(SECOND, 1654.86 * 60, 0) AS Time(0)) AS VARCHAR(5))
Since it's over 24 hours the output is "03:34" I would like for it to be "27:34" or if possible to tell me it will take 3 working days and "03:34" (not sure how that would work).
Thank you in advance! Paul
As explained in the comments, the time data type is not designed to represent any sort of interval or timespan, it is only designed to represent clock time. As such, it is not capable of displaying 27 hours. Instead you need to build this string yourself with methods other than simple CAST as type:
DECLARE #d table(decimal_column decimal(15,2));
INSERT #d(decimal_column) VALUES(1654.86);
SELECT d.decimal_column,
nice_time = CONVERT(varchar(11), FLOOR(h)) + ':'
+ RIGHT('0' + CONVERT(varchar(11), FLOOR(m)), 2)
FROM #d AS d
CROSS APPLY
(
VALUES(d.decimal_column/60, d.decimal_column%60)
) AS extracted(h,m);
Results:
decimal_column
nice_time
1654.86
27:34
Example db<>fiddle
You may have edge cases where you want actual rounding logic instead of FLOOR() - but if you have those cases, include them in your question so we know the desired output.
select CONVERT(VARCHAR, CONVERT(INT, 1654.86/60)) + ':'
+ CONVERT(VARCHAR, CONVERT(INT, 1654.86-(CONVERT(INT, 1654.86/60)*60)))
You can create a function for this query, it is very performance. Because we will not use the same operations in multi sections.

SQL SELECT STATEMENT FOR TODAY

I have been battling for two days now, please could someone give me a bit of assistance on below. I am trying to select data where a date field/column must equal today's date.
SELECT *
FROM stock
WHERE DATE(PREVSELLPRICE1DATE)=DATE(now());
Please assist if you can, I need to rollout this report.
it is better not to manipulate DATE column using functions like TRUNC to mach the date without hour precision (matching year-month-day), it recommended for performance to use something like:
SELECT *
FROM stock
WHERE PREVSELLPRICE1DATE between trunc(sysdate) and trunc(sysdate+1)
this way you'll compare for the required day only + the TRUNC function will be applied only 2 times instead of on each row.
For sql server below is fine:
SELECT *
FROM stock
WHERE CAST(PREVSELLPRICE1DATE as date) = CAST(GETDATE() as date)
Below script
select cast(getdate() as date)
will give you result:
2017-06-29

How to filter SQL by time (greater and less than)?

I want to query a subset from a dataset. Each row has a time stamp of the following format:
2014-04-25T17:25:14
2014-04-25T18:40:16
2014-04-25T18:44:57
2014-04-25T19:10:32
2014-04-25T20:22:12
...
Currently, I use the following query to select a time-based subset:
time LIKE '%2014-04-25T18%' OR time LIKE '%2014-04-25T19%'
This becomes quite complicated when you start to filter by mintutes or seconds.
Is there a way to run a query that such as ...
time > '%2014-04-25T18%' AND time < '%2014-04-25T19%'
A regular expression would be okay, too.
The database is a SpatiaLite database. The time column is of type VARCHAR.
If the date is being treated as a string and based on the example above:
time LIKE '%2014-04-25T18%' AND time <> '%2014-04-25T18:00:00:000'
Otherwise, you could convert the date to seconds since midnight and add 60 minutes to that to create the range part of the filter
DECLARE #test DATETIME = '2014-04-25T17:25:14'
SELECT #test
, CONVERT(DATE,#test) AS JustDate
, DATEDIFF(s,CONVERT(DATETIME,(CONVERT(DATE,#test))), #test) AS SecondsSinceMidnight
-- 60 seconds * 60 minutes * 24 hours = 86400
Thanks to your posts and this answer I came up with this solution:
SELECT * FROM data
WHERE DATETIME(
substr(time,1,4)||'-'||
substr(time,6,2)||'-'||
substr(time,9,2)||' '||
substr(time,12,8)
)
BETWEEN DATETIME('2014-04-25 18:00:00') AND DATETIME('2014-04-25 19:00:00');

Date arithmetic in SQL on DB2/ODBC

I'm building a query against a DB2 database, connecting through the IBM Client Access ODBC driver. I want to pull fields that are less than 6 days old, based on the field 'a.ofbkddt'... the problem is that this field is not a date field, but rather a DECIMAL field, formatted as YYYYMMDD.
I was able to break down the decimal field by wrapping it in a call to char(), then using substr() to pull the year, month and day fields. I then formatted this as a date, and called the days() function, which gives a number that I can perform arithmetic on.
Here's an example of the query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
This yields the following:
difference mydate
2402 20050402
2025 20060306
...
4 20110917
3 20110918
2 20110919
1 20110920
This is what I expect to see... however when I use the same logic in the where clause of my query:
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
where
(
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM
concat substr(char(a.ofbkddt),7,2) ) -- DD
) < 6
I don't get any results back from my query, even though it's clear that I am getting date differences of as little as 1 day (obviously less than the 6 days that I'm requesting in the where clause).
My first thought was that the return type of days() might not be an integer, causing the comparison to fail... according to the documentation for days() found at http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/db2/rbafzmst02.htm, it returns a bigint. I cast the difference to integer, just to be safe, but this had no effect.
You're going about this backwards. Rather than using a function on every single value in the table (so you can compare it to the date), you should pre-compute the difference in the date. It's costing you resources to run the function on every row - you'd save a lot if you could just do it against CURRENT_DATE (it'd maybe save you even more if you could do it in your application code, but I realize this might not be possible). Your dates are in a sortable format, after all.
The query looks like so:
SELECT ofbkddt as myDate
FROM QS36F.ASDF
WHERE myDate > ((int(substr(char(current_date - 6 days, ISO), 1, 4)) * 10000) +
(int(substr(char(current_date - 6 days, ISO), 6, 2)) * 100) +
(int(substr(char(current_date - 6 days, ISO), 9, 2))))
Which, when run against your sample datatable, yields the following:
myDate
=============
20110917
20110918
20110919
20110920
You might also want to look into creating a calendar table, and add these dates as one of the columns.
What if you try a common table expression?
WITH A AS
(
select
days( current date) -
days( substr(char(a.ofbkddt),1,4) concat '-' -- YYYY-
concat substr(char(a.ofbkddt),5,2) concat '-' -- MM-
concat substr(char(a.ofbkddt),7,2) ) as difference, -- DD
a.ofbkddt as mydate
from QS36F.ASDF a
)
SELECT
*
FROM
a
WHERE
difference < 6
Does your data have some nulls in a.ofbkddt? Maybe this is causing some funny behaviour in how db2 is evaluating the less than operation.