how to add 2 varchar columns in sql - sql

I have timediff field as varchar
I want to find sum of this field but it gives error as
"Syntax error converting the varchar value '02:00' to a column of data type int."
My timediff is like
02:00
03:00
04:00
i want to add and should display 9 in sql
please help me
thanks for helping me

You can't use SUM on a varchar column. Take a look at the documentation here.
You haven't given us much information about what you are storing or how you want it summed, but your best bet might be to parse out the number before your colon, convert it to an int and sum that.
Good luck!

If you are talking about MS SQL
You could do something like this
first convert your hour representation to minutes by this
select (CONVERT(int,SUBSTRING('02:00',1,2))*60) +
CONVERT(int,SUBSTRING('02:00',4,2))
Then use that minutes representation to perform addition like this
select
DATEADD(
minute,
(select (CONVERT(int,SUBSTRING('02:00',1,2))*60) +
CONVERT(int,SUBSTRING('02:00',4,2))),
getdate())

If your final goal is to get sum of all datadiff records in hh:mm then first store datediff in minutes instead of hh:mm which you asked here.
How to store DateDiff in minutes:
SELECT DATEDIFF(second,CAST(<timepart> AS DATETIME)
, CAST(<timepart> AS DATETIME))/60.0 AS MIN_DIFF;
For example
SELECT DATEDIFF(second,CAST('10:00 AM' AS DATETIME)
, CAST('11:15 AM' AS DATETIME))/60.0 AS MIN_DIFF;
How to do sum of all minutes in hh:mm
SELECT CAST((<total minutes> / 60) AS VARCHAR(8)) + ':'
+ CAST((<total minutes> % 60) AS VARCHAR(2))
For example
SELECT CAST((390 / 60) AS VARCHAR(8)) + ':'
+ CAST((390 % 60) AS VARCHAR(2))
See this fiddle for all your answers.

Related

PLSQL - convert unix timestamp with millsecond precision to timestamp(6)

I have a unix timstamp with millsecond precision like below:
1523572200000
I need to convert it to timestamp(6). This is the format I need:
05-NOV-14 09.45.00.000000000 AM
(Fyi examples above are not matching dates, just using as example.)
What's the best way to go about this?
Thanks!
The following might work for you (where myunixtimestamp is the name of the column in which your Unix timestamps are stored):
SELECT TIMESTAMP'1970-01-01 00:00:00.000' + NUMTODSINTERVAL(myunixtimestamp/1000, 'SECOND')
FROM mytable;
For example,
SELECT TIMESTAMP'1970-01-01 00:00:00.000' + NUMTODSINTERVAL(1523572200000/1000, 'SECOND')
FROM dual;
gives a result of 2018-04-12 10:30:00.000000000 PM.
Hope this helps.
Assuming that current timestamp is: 1523572200000, try following:
select cast (to_date('1970-01-01', 'YYYY-MM-DD') + 1523572200000/1000/60/60/24 as timestamp) from dual;
where:
to_date('1970-01-01', 'YYYY-MM-DD') is epoch time
<unix_timestamp>/60/60/24 was divided by 1000 miliseconds 60 second and 60 minutes and 24 hours because in oracle we are adding days

Show average difference between two time fields as MM:SS in SQL

I am using SQL Server 2008. I have several rows of start_time and end_time. I want to calculate the average difference between these two times in a MM:SS format.
start_time | end_time
10:15:30 | 10:15:45
10:45:00 | 10:47:30
Row 1 would be a difference of 00:15, and row 2 would be a difference of 02:30. The average of the entire dataset would be 01:23 (1 minute and 23 seconds).
The code I'm using looks like the following, but only returns an integer.
AVG(DATEDIFF(MI,start_time,end_time))
Thanks in advance for your help.
You're close, but you should use DateDiff() to get the average number of seconds between the two fields, rather than the average number of minutes.
With SQL Server 2008 R2, you don't have access to TIMEFROMPARTS() which would simplify the display greatly, so you'll have to convert this into a VARCHAR to get the format you want.
;With AverageSeconds As
(
Select Avg(DateDiff(Second, Start_Time, End_Time))) AvgSec
From YourTable
)
Select Right('00' + Convert(Varchar, (AvgSec / 60)), 2)
+ ':'
+ Right('00' + Convert(Varchar, (AvgSec % 60)), 2)
From AverageSeconds
You can convert the dates in unixtimestamp and then convert the seconds in a string.
Alternatively
right(convert(varchar(20), Dateadd(second, Avg(Datediff(second, Start_Time, End_Time)), 0), 120), 5)

How to print hour values in an hourly report in SQL

I'm building hourly report from SQL Table CONFIRMATION via SQL Query. Query absolutely runs fine and gives proper results as follow:
SELECT DATEPART(hh, CONFIRMATION.DATECOMPLETE) AS hour, sum( CONFIRMATION.QUANTITY) Units
FROM CONFIRMATION
WHERE CONFIRMATION.DATECOMPLETE >= '11/18/2015'
GROUP BY DATEPART(hh, CONFIRMATION.DATECOMPLETE)
I want to change Hour to have follwoing instead of hour number:
Hour Units
10:00 - 11:00 4
11:00-12:00 8
How can I achieve that?
Thanks
You can convert the datetime hour component into a string to format the 10:00-11:00. You can then calculate the end time by adding 1 to the hour component and modulo 24 to wrap around at midnight.
CONVERT(varchar(2),DATEPART(hh,CONFIRMATION.DATECOMPLETE)) + ':00-' + CONVERT(varchar(2), (DATEPART(hh,CONFIRMATION.DATECOMPLETE)+1) % 24) + ':00'
When putting parts of dates together using concatenation, datename() is much better than datepart():
SELECT (DATENAME(hour, c.DATECOMPLETE) + ':00-' +
DATENAME(hour, DATEADD(hour, 1, c.DATECOMPLETE)) + ':00'
) as period,
SUM(c.QUANTITY) as Units
FROM CONFIRMATION c
WHERE c.DATECOMPLETE >= '2015-11-18'
GROUP BY (DATENAME(hour, c.DATECOMPLETE) + ':00-' +
DATENAME(hour, DATEADD(hour, 1, c.DATECOMPLETE)) + ':00'
);
In addition:
Use ISO standard date formats. Either YYYY-MM-DD or YYYYMMDD.
Table aliases make the query easier to write and to read.

How to convert Epoch time to date?

Hi I have a column with number datatype
the data like 1310112000 this is a date, but I don't know how to make it in an understandable format:
ex: 10-mar-2013 12:00:00 pm
Can any one please help me.
That is EPOCH time: number of seconds since Epoch(1970-01-01). Use this:
SELECT CAST(DATE '1970-01-01' + ( 1 / 24 / 60 / 60 ) * '1310112003' AS TIMESTAMP) FROM DUAL;
Result:
08-JUL-11 08.00.03.000000000 AM
Please try
select from_unixtime(floor(EPOCH_TIMESTAMP/1000)) from table;
This will give the result like E.g: 2018-03-22 07:10:45
PFB refence from MYSQL
In Microsoft SQL Server, the previous answers did not work for me. But the following does work.
SELECT created_time AS created_time_raw,
dateadd( second, created_time, CAST( '1970-01-01' as datetime ) ) AS created_time_dt
FROM person
person is a database table, and created_time is an integer field whose value is a number of seconds since epoch.
There may be other ways to do the datetime arithmetic. But this is the first thing that worked. I do not know if it is MSSQL specific.

Efficient way to convert second to minute and seconds in sql server 2005

Suppose I have 90 seconds. If I want to display the result in terms of minutes and second, I do it by using
select Time= '0' + CAST( 90/60 as varchar(2)) + ':' + CAST( 90%60 as varchar(2))
The output is
Time
01:30
I have appended 0(zero) because if you do a select getdate() the output will be
yyyy-mm-dd hh:mm:ss:ms
What is the standard way and recommended practice to do such a conversion?
Thanks
With hours:
SELECT CONVERT(CHAR(8),DATEADD(second,90,0),108)
00:01:30
Ignoring hours:
SELECT RIGHT(CONVERT(CHAR(8),DATEADD(second,90,0),108),5)
01:30
Try this:
select convert(varchar(10), dateadd(second, 15794, 0), 108)
One of the first things I do on a fresh SQL database is add a Timespan function similar to this one (although I tend to include days and milliseconds as well):
CREATE FUNCTION dbo.TimeSpan
(
#Hours int,
#Minutes int,
#Seconds int
)
RETURNS datetime
AS BEGIN
RETURN DATEADD(SS, #Hours * 3600 + #Minutes * 60 + #Seconds, 0)
END
Then you can format this however you want:
SELECT SUBSTRING(CONVERT(char(8), dbo.TimeSpan(0, 0, 90), 108), 4, 5)
It might look more complicated at first, but the ability to reuse the TimeSpan function comes in very handy over time. For me it feels like a hack to always be writing DATEADD calls against 0 or '1753-01-01'.