SQL Server 2005 DateTime math - sql-server-2005

I'm trying to get the amount of time spent on something. I have the DateTime for the start and end of the thing in two columns. I can do:
cnext.CreatedDate - c.CreatedDate
which results in something like this:
1900-01-01 00:00:19.190
which means they spent 19.19 seconds on the thing. That's great for each row but i would like to group by the specific thing and sum up the time spent on each thing:
SUM(cnext.CreatedDate - c.CreatedDate)
but I get a:
Operand data type datetime is invalid for sum operator.
How should i go about getting the total time is I can't sum up DateTime types?

You can't SUM datetime values. This is like taking the square root of a string.
Try:
SUM(DATEDIFF(SECOND, c.CreatedDate, cnext.CreatedDate))
Or if you want greater precision:
SUM(DATEDIFF(MILLISECOND, c.CreatedDate, cnext.CreatedDate))

If the date potion is 1/1/1900, convert the dates to floats, subtract them, and convert the result back to datetime.

Related

Calculate time difference in SQL

We have two columns in SQL. one is total_work_time & next is total_exeption_time & both column data type is varchar
total_work_time value is 07:15:00
total_exeption_time value is 01:15:00
So I need to subtract total_work_time - total_exeption_time and the result will be 06:00:00.
I have tried with concat(DATEDIFF(HOUR,total_exeption_time,total_work_time),':', DATEDIFF(MINUTE,total_exeption_time,total_work_time))
But the result is 6:360. from this, 360 is the problem, it taken total minutes. I need the result structure like 06:00:00. How to fix this issue using SQL Server.
You should be storing time values in a TIME datatype - using the correct datatype is not only a best practice but will reduce the problems you face in future.
You can convert your VARCHAR values to TIME and then use the following calculation which takes the difference in seconds (your lowest unit of interest one assumes) and creates a new TIME result.
DECLARE #total_work_time TIME = '07:15:00', #total_exeption_time TIME = '01:15:00';
SELECT CONVERT(TIME, DATEADD(SECOND, DATEDIFF(SECOND, #total_exeption_time, #total_work_time), '00:00'));

SQL how i can convert from datetime to total hours?

I do this query and the result is a datetime, i try so much variants, but nothing work it... I want the result to be displayed in the number of total hours, like (in this case): 25:01:05 because i have 2 days en this datetime, I have had results like 01:01:05 which is when it only subtracts the hours from the datetime. I would like that as well as add the hours by the number of days, do it with the months if it can be
The time datatype in SQL Server only holds up to 24 hours.
I would recommend decimal hours instead:
select datediff(second, 0, calchstrabajos) / (60.0 * 60)
Note: I switched from millisecond to second because that is usually sufficient.
If you want this in the form of HH:MM:SS, then you would need to convert to a string. I don't recommend that.

Subtracting two times to get duration

I am trying to subtract departure time from arrival time to get the duration of trips.
The arrival/departure is in the format of HH:MM.
I'm using postgresql, the time columns just say 'string' for how they are defined. A friend helped me cast them as integers, but I'm still stick at this point:
SELECT x, cast (table1.arrival as integer) - cast (table.1departure as integer), sum(y), count(*)
FROM table1 INNER JOIN table2
ON .....
GROUP BY .....
ORDER BY....
A friend told me this but I'm not totally sure what he means: "No you need to create a new variable for just minutes. 1:30 = 90 minutes. Cast that as integer then compute." How do I do this?
If the column is indeed a varchar (or text) then you need to first cast the column to a proper time.
SELECT x, table1.arrival::time - table.1departure::time, sum(y), count(*)
FROM table1 INNER JOIN table2
ON .....
GROUP BY .....
ORDER BY.
The above will fail if the time stored in the columns is not a properly formatted time in 24 hour format (e.g. 22:40)
The result of time - time is an interval. If you want to get the result in minutes, you need to extract them from the interval:
extract(epoch from table1.arrival::time - table.1departure::time) / 60
extract(epoch ..) returns the seconds in the interval that's why you need to divide it by 60 to get minutes.
This will however not work properly if the arrival and departure time are not on the same day (e.g. departure is at 23:25 and arrival is the next day at 07:23)
Unrelated but: you should never store dates, times or timestamps in varchar or text columns. Always use the proper data type.
If your RDBMS is Mysql you can use the MySQL DATEDIFF() Function
For example :
SELECT DATEDIFF(arrivale,departure) AS DiffDate
I assume here that the arrivale and the departure are in the same day.
And that arrivale and departue are TimeDate formated like HH:MM.

Subtract Two Date Time Values in SQL Server

I want to subtract two DateTime values:
I have Start DateTime #2015-06-14 23:00:00# End Date Time #2015-06-15 01:01:00#
I want to get the duration by time format like HH:MM:SS and update it in the duration column. I tried the following code but, it doesn't work.
update [ZainJTA].[dbo].[TBL_Justification]
set [Justification_Event_Duration]=CONVERT(Datetime,(DateDiff("n",[Justification_From],[Justification_TO])/60/24),108)
DATEDIFF returns an INT, so dividing it by two other INTs is going to give you - another INT, most likely zero.
Try:
CONVERT(Datetime,(DateDiff(s,[Justification_From],[Justification_TO])/60.0/60/24),108)
(the 60.0 will trigger conversion to a floating point format.)
However, it'd probably make more sense to store it as a number of seconds (integer), and only do the CONVERT when you output it to display.
To display as just the time, with no day/year part, you'll also need to do a second conversion:
CONVERT(VARCHAR, CONVERT(Datetime,
(DateDiff(s,[Justification_From],[Justification_TO])/60.0/60/24),108),108)

Convert SQL server datetime fields to compare date parts only, with indexed lookups

I've been doing a convert(varchar,datefield,112) on each date field that I'm using in 'between' queries in SQL server to ensure that I'm only accounting for dates and not missing any based on the time part of datetime fields.
Now, I'm hearing that the converts aren't indexable and that there are better methods, in SQL Server 2005, to compare the date part of datetimes in a query to determine if dates fall in a range.
What is the optimal, indexable, method of doing something like this:
select * from appointments
where appointmentDate>='08-01-2008' and appointmentDate<'08-15-2008'
The best way to strip the time portion of a datetime field is using datediff and dateadd functions.
DateAdd(day, datediff(day,0, MydateValue), 0)
This takes advantedge of the fact that SQL Server stores dates as two integers, one representing the number of days since day "0" - (1 jan 1900), and the second one which represents the number of ticks (each tick is about 3.33 ms) since midnight (for the time) *.
the formula above simply has to only read the first integer. There is no conversion or processing required, so it is extremely fast.
To make your queries use an index... use this formula on the input filtering parameters first, or on the "other" side of the equal sign from the tables date time field, so that the query optimizer does not have to run the calculation on every datetime field in the table to determine which rows satisfy the filter predicate. This makes your search argument "SARG-able" (Search ARGument)
Where MyDateTimeColumn > DateAdd(day,
datediff(day,0, #MydateParameter), 0) -- SARG-able
rather than
Where DateAdd(day, datediff(day,0,
MyDateTimeColumn ), 0) > #MydateParameter -- Not SARG-able
* NOTE. Internally, the second integer (the time part) stores ticks. In a day there are 24 x 60 X 60 X 300 = 25,920,000 ticks (serendipitously just below the max value a 32 bit integer can hold). However, you do not need to worry about this when arithmetically modifying a datetime... When adding or subtracting values from datetimes you can treat the value as a fraction as though it was exactly equal to the fractional portion of a day, as though the complete datetime value was a floating point number consisting of an integer portion representing the date and the fractional portion representing the time). i.e.,
`Declare #Dt DateTime Set #Dt = getdate()
Set #Dt = #Dt + 1.0/24 -- Adds one hour
Select #Dt
Set #Dt = #Dt - .25 -- Moves back 6 hours
Select #Dt`
Converting numeric types to string values (a type of Boxing) is not the best performing method of doing what you are looking for. Its not really about index-able, because the actual column type is date time.
If you are looking for the best way query for dates, then your example is right, but you may want to take into account the 3 ms precision difference in MSSQL. It can mean that records from one day can show up in another day's result.
This
select * from appointments where appointmentDate>='08-01-2008' and appointmentDate<'08-15-2008'
Should be this
select * from appointments where appointmentDate>='08-01-2008' and appointmentDate<='08-14-2008 23:59:59.996'
It's correct - doing the conversion will execute the conversion for every row queried. It's better to leave the date columns as dates, and pass in your where clauses as dates:
select * from appointments where appointmentdate between
'08/01/2008' AND '08/16/2008'
Note: Leaving off the time means midnight (00:00.000), so you will include all times for 08/01, and all times from 08/15, and anything that is exactly 08/16/2008 00:00:00
Have a computed persisted column calculate the expression you need. If columns are computed and persisted, they can also be indexed.
There is also the way described at http://www.stillnetstudios.com/comparing-dates-without-times-in-sql-server/
SELECT CAST(FLOOR(CAST( getdate() AS float )) AS datetime)