How to subtract 2 dates in SQL and get HH:MI:SS - sql-server-2005

How to subtract 2 dates in SQL and get HH:MI:SS
(SQL Server 2005)
Iam using MS Access to do this.
Example:
23-09-2013 15:43:59
23-09-2013 15:43:33 -
Wanted answer 00:00:26

Use DateDiff, for the timespan format use string methods:
SELECT Diff =
right('0'+ rtrim(CAST(DateDiff(hour, #dt2, #dt1) AS VARCHAR(2))), 2) + ':' +
right('0'+ rtrim(CAST(DateDiff(minute, #dt2, #dt1)AS VARCHAR(2))), 2) + ':' +
right('0'+ rtrim(CAST(DateDiff(second, #dt2, #dt1)AS VARCHAR(2))), 2)
Demo

If the two dates are in a range of 24 hours you can use this code:
SELECT LEFT(CONVERT(VARCHAR, DATEADD(SECOND, DATEDIFF(SECOND, #Date2, #Date1), 0), 114), 8)
Source: How to convert Seconds to HH:MM:SS using T-SQL
If you can't use native SQL query in your Access program, give a look at these links (Access syntax):
LEFT
DATEADD
DATEDIFF
Maybe you can manipulate the resulting string without using CONVERT (not supported in Access).

Related

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 convert format to12 HRS instead of 24hrs SQL

SELECT
Warehouses.Name, CONVERT(TIME,AirwayBillTrucks.CheckOutTime) AS CheckOutTime,
Assuming you are using SQL Server -
This will fetch you 12hr format
SELECT CONVERT(VARCHAR, Your_column_Name, 100) AS 12_hr_format
To show just the time
SELECT RIGHT(CONVERT(VARCHAR, Your_column_Name, 100), 7) AS time_in_12hr_format
OR simply use the code 108
SELECT CONVERT(VARCHAR, Your_column_Name, 108) AS time_in_12hr_format
Conversion -
100 - mon dd yyyy hh:miAM (or PM)
121 - yyyy-mm-dd hh:mi:ss.mmm(24h)
You can see all the type of format conversion here at Microsoft CAST and CONVERT
If SQL Server 2012+
Select Format(GetDate(),'hh:mm:ss tt')
Returns
03:55:30 PM

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.

SQL Query to Select * From Table where date is between 7 days ago and now

I am trying to write a simple query in SQL Server (2005 express). The purpose is to only choose data between now and 7 days ago. I cannot seem to get the GETDATE function to work in this example... Any ideas?
**PS - The date time in the column is in EPOCH so I believe the issue may be stemming from here with the datatype...
Select * From TB_Data
where TB_Data.nDate <= GETDATE()-7)
Adding a parenthesis before the GETDATE() function will work.
Select * From TB_Data
where TB_Data.nDate <= (GETDATE() - 7)
With EPOCH, you will need to convert the date before comparing:
DATEADD(s, TB_Data.nDate, '19700101')
So the full query is:
Select * From TB_Data
where DATEADD(s, TB_Data.nDate, '19700101') <= (GETDATE() - 7)

how to add 2 varchar columns in 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.