Finding Average Time Length in SQL - 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+)$)';

Related

Snowflake converting numeric value into HHMMSS format

I have a column that has number in it in the format of HHMMSS but the number is not consistent (not all have six digits), ex: "83455" "153651" "91251".
The number 83455 would mean 8:34 am and 55 as SS. I tried converting into varchar and use TO_TIME but the output is not the same as it is. Similarly, I also tried converting into timestamp then get the time from it but it just won't work. The output I want here would be 8:34:55, what is the best way to convert the number?
Try this. I split hours minutes and seconds and then concatenate them into time format.
SELECT
CAST(FLOOR(col / 10000) || ':' ||
FLOOR(MOD(col / 100, 100)) || ':' ||
MOD(col, 100) AS TIME) AS converted_time
FROM
yourtable
MOD()
An alternative approach is to use the built in function for this task.
TRY_TO_TIME().
Sometimes the built in functions are easier to read, understand, less typing, optimized (runs faster/cheaper).
SELECT
TRY_TO_TIME (DONT_WASTE, 'HH24MISS" )VOLIA
,TO_CHAR (VOLIA, 'HH12:MI:SS AM' ) AM_PM
FROM
(SELECT '83455 'DONT_WASTE UNION SELECT '153651 'UNION SELECT '91251')
The core of this problem is the format string was wrong
MM is Month, MI is minutes.
The first path I went down was slicing the string up, but the TO_TIME/TRY_TO_TIME both handle the smaller string of the pre lunchtime, but does not handle no hours, for that you might need to pad if you have such truncated values from number I assume:
select column1
,try_to_time(column1, 'HH24MMSS') as wrong
,try_to_time(column1, 'HH24MISS') as r1
,lpad(column1, 6, '0') as p
,try_to_time(p, 'HH24MISS') as r2
from values
('83455'),
('153651'),
('91251'),
('1251')
;
COLUMN1
WRONG
R1
P
R2
83455
null
08:34:55
083455
08:34:55
153651
null
15:36:51
153651
15:36:51
91251
09:00:51
09:12:51
091251
09:12:51
1251
12:00:01
null
001251
00:12:51
Thus inline it would be:
try_to_time(lpad(column1, 6, '0'), 'HH24MISS')

Rename Column name in Pivot query and format its time value in format HH:MM:SS

I am preparing one report for which I need to have sum of time taken by various processes in column 2.
I am sharing small snippet in which I am not able to figure out. Below is the query.
SELECT DISTINCT *
FROM CTE_NAME
PIVOT ( SUM(TIME) FOR ACTIVITY IN ( NULL
,Process 1
,Process 2
)
) order by 2 desc
Things to be noted:-
hours_diff is the value calculated in a CTE expression above this shared snippet
hours_diff is of date type.
Things to be done:-
It is required to change the Column name NULL to TOTAL_TIME
It is required to convert the value of TIME to HH:MM:SS
Things I have tried:-
I tried using SUM(TIME) AS TOTAL_TIME ... it didn't seem to work. Also after that I tried replacing NULL with TOTAL_TIME but it changed in a way that TIME values of Process 1 shifted towards column 2.
In order to convert the time value (which is in seconds). I have this previously used TO_CHAR(TRUNC(sec_diff/3600),'FM9900') || ':' || TO_CHAR(TRUNC(MOD(sec_diff,3600)/60),'FM00') || ':' || TO_CHAR(MOD(sec_diff,60),'FM00') as time_diff. But as I am unable to fetch the column from above snippet I am not able to convert the values to HH:MM:SS
If I convert the value of TIME inside CTE then SUM function in SELECT query throws error Invalid Number as the value being passed to SUM function is in format HH:MM:SS
For giving name to the column, you can provide name in IN list of PIVOT as follows:
SELECT DISTINCT *
FROM CTE_NAME
PIVOT ( SUM(TIME) FOR ACTIVITY
IN ( NULL as TOTAL_TIME, -- THIS
,Process 1
,Process 2
)
) order by 2 desc;
To calculate HH:MI:SS from seconds, use this in select.(works for seconds in diff is less than 86400(1 day)
TO_CHAR(TRUNC(SYSDATE) + INTERVAL '1' SECOND * YOUR_COLUMN_SECONDS, 'HH24:MI:SS')
Or following will work for any bigger values
Lpad(Trunc(your_column_seconds/86400),2,'0')
|| ':' ||
Lpad(Trunc(your_column_seconds/1440),2,'0')
|| ':' ||
Lpad(Trunc(your_column_seconds/60),2,'0')
Note: column name of seconds difference generated by pivot should be used in above expression.

Can I add this format in sqlite3

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

storing date in 'CCYYMMDD' format in Teradata

I would like to store dates in the format CCYYMMDD in Teradata, but I fail to do so. Find below what I tried so far:
query 1:
SEL CAST(CAST(CURRENT_DATE AS DATE FORMAT 'YYYYMMDD') AS VARCHAR(8))
-- Output: 20191230 ==> this works!
query 2:
SEL CAST(CAST(CURRENT_DATE AS DATE FORMAT 'CCYYMMDD') AS VARCHAR(8))
-- output: SELECT Failed. [3530] Invalid FORMAT string 'CCYYMMDD'.
It seems that the CCYYMMDD is not available in Teradata right away. Is there a workaround?
Tool used: Teradata SQL assistant
Internally, dates are stored as integers in Teradata. So when you say you want to store them in a different format, I don't think you can do that. But you can choose how to display / return the values.
I'm sure there's a cleaner way to get the format you want, but here's one way:
WITH cte (mydate) AS (
SELECT CAST(CAST(CURRENT_DATE AS DATE FORMAT 'YYYYMMDD') AS CHAR(8)) AS mydate
)
SELECT
CAST(
(CAST(SUBSTRING(mydate FROM 1 FOR 2) AS INTEGER) + 1) -- generate "century" value
AS CHAR(2) -- cast value as string
) || SUBSTRING(mydate FROM 3) AS new_date -- add remaining portion of date string
FROM cte
SQL Fiddle - Postgres
You'd have to add some extra logic to handle years before 1000 and after 9999. I don't have a TD system to test, but give it a try and let me know.

How to get sum of string data in SQL?

I have a table with column name 'Working_hours', column type is String and data of that column looks like below.
I want to sum of those data.
Is there any way to achieve it or any idea.
thanks in advance
0:00:11
0:00:08
0:00:01
0:00:29
0:01:25
0:00:06
0:00:12
0:00:26
0:00:01
0:01:41
0:00:01
SELECT
convert(char(20),dateadd(second,SUM
(
DATEPART(hh,(convert(datetime,Working_hours,1))) * 3600 +
DATEPART(mi, (convert(datetime,Working_hours,1))) * 60 +
DATEPART(ss,(convert(datetime,Working_hours,1)))),0),108
)
AS Working_hours
FROM tblTime
You can use this Query....In Sql server..
convert this to epoch time.
for mssql
select sum(DATEDIFF(s, '1900-01-01 00:00:00', cast(time_column as datetime))) from table
result is sum in seconds.
that depends a bit on what database you are using
generally you have to convert or cast to time and sum then. Eg.g postgresql:
SELECT SUM(fieldname::time) FROM table
The ::time does the casting to time.
Microsoft sql-server (don't have one at hand right now so take with a grain of salt):
SELECT sum(CONVERT( TIME, fieldname )) FROM table
If you have some other database look up how to cast or convert a string to a time...