Float as DateTime - sql-server

SQL Server 2008
I almost have, I think, what I'm looking to do. I'm just trying to fine tune the result. I have a table that stores timestamps of all transactions that occur on the system. I'm writing a query to give an average transaction time. This is what I have so far:
With TransTime AS (
select endtime-starttime AS Totaltime
from transactiontime
where starttime > '2010-05-12' and endtime < '2010-05-13')
Select CAST(AVG(CAST(TotalTime As Float))As Datetime)
from TransTime
I'm getting the following result:
1900-01-01 00:00:00.007
I can't figure out how to strip the date off and just display the time, 00:00:00:007. Any help would be appreciated. Thank you.

You want to cast as a TIME.
With TransTime AS (
select endtime-starttime AS Totaltime
from transactiontime
where starttime > '2010-05-12' and endtime < '2010-05-13')
Select CAST(AVG(CAST(TotalTime As Float))As TIME(7))
from TransTime

It's that first subtraction that's your problem, and why are you casting the result to DATETIME (or even TIME)?
With TransTime AS
(
-- get time in milliseconds
select DATEDIFF(ms, starttime, endtime) AS Totaltime
from transactiontime
where starttime > '2010-05-12' and endtime < '2010-05-13'
)
Select AVG(CAST(TotalTime As Float)) AS average_time_in_msec
FROM TransTime

You probably want to use the DATEPART function to do this. Check out the documentation here.

Related

Can the LAG function return a single DATE value that is not NULL

I have a table containing 3 columns [MONTHNAME], [MONTHSTART] and [MONTHEND]. For reporting, I need to group all prior months together but leave the current month grouped by weeks. To do this I need to get the prior month's ending date. Below is the query I am using and it works properly, but is there a better way of determining the prior month's ending date without creating a table or using CTE with the LAG function? There was no way I found to get the LAG function to return a single value so I had to use the following. Our month ending dates do not fall on the calendar month ending date so I am pulling the data from a custom calendar.
DECLARE #tblMonthEndingDates TABLE
([MONTHSTART] DATE
,[MONTHEND] DATE
)
INSERT INTO #tblMonthEndingDates
VALUES('01-01-2018', '01-26-2018'),
('01-27-2018', '03-02-2018'),
('03-03-2018', '03-30-2018'),
('03-31-2018', '04-27-2018'),
('04-28-2018', '06-01-2018'),
('06-02-2018', '06-30-2018'),
('07-01-2018', '07-27-2018'),
('07-28-2018', '08-31-2018'),
('09-01-2018', '09-28-2018'),
('09-29-2018', '10-26-2018'),
('10-27-2018', '11-30-2018'),
('12-01-2018', '12-31-2018')
DECLARE #dtTbl TABLE(RN INT
,MS DATE
,ME DATE
);
INSERT INTO #dtTbl
SELECT ROW_NUMBER() OVER(ORDER BY [MONTHSTART]) AS ROWNUM
,[MONTHSTART]
,[MONTHEND]
FROM #tblMonthEndingDates;
WITH cteDt
AS
(
SELECT d2.[MS]
,LAG(d1.[ME]) OVER(ORDER BY d1.[MS]) AS PRIORDT
,d2.[ME]
FROM #dtTbl d1
LEFT JOIN #dtTbl d2 ON d1.[RN] = d2.[RN]
)
SELECT [PRIORDT]
FROM cteDt
WHERE [MS] <= GETDATE() AND [ME] >= GETDATE()
So for this month I would want 09-28-2018 as the return value which the query does, I just want to know if there is a better/shorter way of returning that value.
You can do something like this:
Select
Max(MonthEnd)
From #tblMonthEndingDates
Where MonthEnd <= GetDate()
That will give you the most recent MonthEnd date before or on today's date. Obviously, if you need strictly before, you'd use < rather than <=
I used this query to get the start and end dates for the last #n months. You can adapt to meet your needs.
declare #t table (SD date,ED date)
declare #i int = 0
,#SD date
,#ED date
,#datetoEval date
,#EOM date
,#n int = 60
while(#i<=#n)
BEGIN
set #datetoEval = DATEADD(month,-1*#i,getdate())
set #SD = cast(cast(month(#datetoEval) as varchar(2)) + '/1/' + cast(year(#datetoEval) as varchar(4)) as DATE)
set #ED = dateadd(day,-1,DATEADD(MONTH,1,#SD))
insert into #t
values(#SD,#ED)
set #i=#i+1
END
select * from #t
I was overthinking it. Last month ended the day before this one started.
SELECT DATEADD(DAY, -1, MONTHSTART) AS MONTHEND
FROM #tblMonthEndingDates
WHERE
GETDATE() BETWEEN MONTHSTART AND MONTHEND

Ugly table query

I have inherited this table and trying to optimize the queries. I am stuck with one query. Here is the table information
RaterName - varchar(24) - name of the rater
TimeTaken - varchar(12) - is stored as 00:10:14:8
Year - char(4) - is stored as 2014
I need
distinct list of raters, total count for the rater, sum(TimeTaken) for rater, avg(timetaken) for rater (for a given year)
I also need sum(timetaken) and avg(TimeTaken) for all the raters (for a given year)
Here is the query that I have come up with for #1... I would like the sum and avg to be like hh:mm:ss. How can I do this?
SELECT
[RaterName]
, count(*) as TotalRatings
, SUM((DATEPART(hh,convert(datetime, timetaken, 101))*60)+DATEPART(mi,convert(datetime, timetaken, 101))+(DATEPART(ss,convert(datetime, timetaken, 101))/(60.0)))/60.0 as TotalTimeTaken
, AVG((DATEPART(hh,convert(datetime, timetaken, 101))*60)+DATEPART(mi,convert(datetime, timetaken, 101))+(DATEPART(ss,convert(datetime, timetaken, 101))/(60.0)))/60.0 as AverageTimeTaken
FROM
[dbo].[rating]
WHERE
year = '2014'
GROUP BY
RaterName
ORDER BY
RaterName
Output:
RaterName TotalRatings TotalTimeTaken AverageTimeTaken
================================================================
Rater1 257 21.113609 0.082154
Rater2 747 41.546106 0.055617
Rater3 767 59.257218 0.077258
Rater4 581 37.154163 0.063948
Can I incorporate #2 in this query or write a second query and drop group by from it?
On the front end, I am using C#.
WITH data ( raterName, timeTaken )
AS (
SELECT raterName,
DATEDIFF(MILLISECOND, CAST('00:00' AS TIME),
CAST(timeTaken AS TIME))
FROM rating
WHERE CAST([year] AS INT) = 2014
)
SELECT raterName, COUNT(*) AS totalRatings,
SUM(timeTaken) AS totalTimeTaken, avg(timeTaken) AS averageTimeTaken
FROM data
GROUP BY raterName
ORDER BY raterName;
PS: If you don't want milliseconds, can make that Second or Minute.
EDIT: On your C# frontend you can make the Milliseconds or Seconds to a TimeSpan which would give you the format when you use ToString. ie:
var ttt = TimeSpan.FromSeconds(totalTimeTaken).ToString();

How to query DATETIME field using only date in Microsoft SQL Server?

I have a table TEST with a DATETIME field, like this:
ID NAME DATE
1 TESTING 2014-03-19 20:05:20.000
What I need a query returning this row and every row with date 03/19/2014, no matter what the time is. I tried using
select * from test where date = '03/19/2014';
But it returns no rows. The only way to make it work that I found is to also provide the time portion of the date:
select * from test where date = '03/19/2014 20:03:02.000';
use range, or DateDiff function
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test
where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the
time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test
Add DateOnly As
DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test
Add DateOnly As
Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test
where DateOnly = '03/19/2014'
Simple answer;
select * from test where cast ([date] as date) = '03/19/2014';
I am using MySQL 5.6 and there is a DATE function to extract only the date part from date time. So the simple solution to the question is -
select * from test where DATE(date) = '2014-03-19';
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
This works for me for MS SQL server:
select * from test
where
year(date) = 2015
and month(date) = 10
and day(date)= 28 ;
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
This is a realy bad answer. For two reasons.
1.
What happens with times like 23.59.59.700 etc.
There are times larger than 23:59:59 and the next day.
2.
The behaviour depends on the datatype.
The query behaves differently for datetime/date/datetime2 types.
Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.
select convert (varchar(40),convert(date , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))
-- For date the value is 'chopped'.
-- For datetime the value is rounded up to the next date. (Nearest value).
-- For datetime2 the value is precise.
use this
select * from TableName where DateTimeField > date() and DateTimeField < date() + 1
Try this
select * from test where Convert(varchar, date,111)= '03/19/2014'
you can try this
select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';
There is a problem with dates and languages and the way to avoid it is asking for dates with this format YYYYMMDD.
This way below should be the fastest according to the link below. I checked in SQL Server 2012 and I agree with the link.
select * from test where date >= '20141903' AND date < DATEADD(DAY, 1, '20141903');
Bad habits to kick : mis-handling date / range queries
You can use this approach which truncates the time part:
select * from test
where convert(datetime,'03/19/2014',102) = DATEADD(dd, DATEDIFF(dd, 0, date), 0)
-- Reverse the date format
-- this false:
select * from test where date = '28/10/2015'
-- this true:
select * from test where date = '2015/10/28'
Simply use this in your WHERE clause.
The "SubmitDate" portion below is the column name, so insert your own.
This will return only the "Year" portion of the results, omitting the mins etc.
Where datepart(year, SubmitDate) = '2017'
select *, cast ([col1] as date) <name of the column> from test where date = 'mm/dd/yyyy'
"col1" is name of the column with date and time
<name of the column> here you can change name as desired
select *
from invoice
where TRUNC(created_date) <=TRUNC(to_date('04-MAR-18 15:00:00','dd-mon-yy hh24:mi:ss'));
Test this query.
SELECT *,DATE(chat_reg_date) AS is_date,TIME(chat_reg_time) AS is_time FROM chat WHERE chat_inbox_key='$chat_key'
ORDER BY is_date DESC, is_time DESC
select * from invoice where TRANS_DATE_D>= to_date ('20170831115959','YYYYMMDDHH24MISS')
and TRANS_DATE_D<= to_date ('20171031115959','YYYYMMDDHH24MISS');
SELECT * FROM test where DATEPART(year,[TIMESTAMP]) = '2018' and DATEPART(day,[TIMESTAMP]) = '16' and DATEPART(month,[TIMESTAMP]) = '11'
use trunc(column).
select * from test t where trunc(t.date) = TO_DATE('2018/06/08', 'YYYY/MM/DD')

how to query where date with time = date without time in ms sql

I want to do a query with dates this is my sample tsql:
select * from Bookings where StartTime = '2/15/2014'
the starttime has value '2/15/2014 12:00:00 AM'
when I query where StartTime = date with no time the result is 0
Anybody can help how to do this?
thanks
Try like this
SELECT * FROM Bookings WHERE Convert(VARCHAR(10),StartTime,101) = Convert(Varchar(10),'2/15/2014',101)
If you are using SQL SERVER 2012
Try this
SELECT * FROM Bookings WHERE FORMAT(StartTime,'M/dd/yyyy') = FORMAT('2/15/2014','M/dd/yyyy')
SQL FORMAT
The best way to do this is with a simple comparison:
select *
from Bookings
where StartTime >= cast('2014-02-15' as date) and StartTime < cast('2014-02-14' as date);
This is the safest method of comparison, because it will take advantage of an index on StartTime. This property is called "sargability".
In SQL Server, casting to a date should also be sargable, so you could also do:
select *
from Bookings
where cast(StartTime as date) = cast('2014-02-15' as date) ;
'2/15/2014' can be interpreted different depending on your locale. Try using the ISO date literal '2014-02-15', which is independent of the locale.
select * from Bookings where StartTime = '2014-02-15'
Or if StartTime includes hours:
select * from Bookings where StartTime >= '2014-02-15' and StartTime < '2014-02'16'
I believe you could also do this:
select * from Bookings where StartTime::date = '2014-2-15'

SQL Datediff in seconds with decimal places

I am trying to extract the difference between two SQL DateTime values in seconds, with decimal places for some performance monitoring.
I have a table, "Pagelog" which has a "created" and "end" datetime. In the past I have been able to do the following:
SELECT DATEDIFF(ms, pagelog_created, pagelog_end)/1000.00 as pl_duration FROM pagelog
However I have started getting the following error:
Msg 535, Level 16, State 0, Line 1
The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.
I have seen numerous responses to this error stating that I should use a less precise unit of measurement. But this hardly helps when I need to distinguish between 2.1 seconds and 2.9 seconds, because DATEDIFF(s,..,..) will return INT results and lose the accuracy I need.
I originally thought that this had been caused by a few values in my table having a huge range but running this:
SELECT DATEDIFF(s, pagelog_created, pagelog_end) FROM pagelog
ORDER BY DATEDIFF(s, pagelog_created, pagelog_end) DESC
Returns a max value of 30837, which is 8.5 hours or 30,837,000 milliseconds, well within the range of a SQL INT as far as I know?
Any help would be much appreciated, as far as I can tell I have two options:
Somehow fix the problem with the data, finding the culprit values
Find a different way of calculating the difference between the values
Thanks!
The StackOverflow magic seems to have worked, despite spending hours on this problem last week, I re-read my question and have now solved this. I thought I'd update with the answer to help anyone else who has this problem.
The problem here was not that there was a large range, there was a negative range. Which obviously results in a negative overflow. It would have been helpful if the SQL Server error was a little more descriptive but it's not technically wrong.
So in my case, this was returning values:
SELECT * FROM pagelog
WHERE pagelog_created > pagelog_end
Either remove the values, or omit them from the initial result set!
Thanks to Ivan G and Andriy M for your responses too
You can try to avoid overflow like this:
DECLARE #dt1 DATETIME = '2013-01-01 00:00:00.000'
DECLARE #dt2 DATETIME = '2013-06-01 23:59:59.997'
SELECT DATEDIFF(DAY, CAST(#dt1 AS DATE), CAST(#dt2 AS DATE)) * 24 * 60 * 60
SELECT DATEDIFF(ms, CAST(#dt1 AS TIME), CAST(#dt2 AS TIME))/1000.0
SELECT DATEDIFF(DAY, CAST(#dt1 AS DATE), CAST(#dt2 AS DATE)) * 24 * 60 * 60
+ DATEDIFF(ms, CAST(#dt1 AS TIME), CAST(#dt2 AS TIME))/1000.0
First it gets number of seconds in whole days from the DATE portion of the DATETIME and then it adds number of seconds from the TIME portion, after that, it just adds them.
There won't be error because DATEDIFF for minimum and maximum time in TIME data type cannot produce overflow.
You could of course do something like this:
SELECT
DATEDIFF(ms, DATEADD(s, x.sec, pagelog_created), pagelog_end) * 0.001
+ x.sec AS pl_duration
FROM pagelog
CROSS APPLY (
SELECT DATEDIFF(s, pagelog_created, pagelog_end)
) x (sec)
;
As you can see, first, the difference in seconds between pagelog_created and pagelog_end is taken, then the seconds are added back to pagelog_created and the difference in milliseconds between that value and pagelog_end is calculated and added to the seconds.
However, since, as per your investigation, the table doesn't seem to have rows that could cause the overflow, I'd also double check whether that particular fragment was the source of the error.
with cte as(
select rownum = row_number() over(partition by T.TR_ID order by T.[date]),
T.* from [dbo].[TR_Events] T
)
select cte.[date],nex.[date],convert(varchar(10),datediff(s, cte.[date], nex.[date])/3600)+':'+
convert(varchar(10),datediff(s, cte.[date], nex.[date])%3600/60)+':'+
convert(varchar(10),(datediff(s,cte.[date], nex.[date])%60))
from cte
left join cte prev on prev.rownum = cte.rownum - 1
left join cte nex on nex.rownum = cte.rownum + 1

Resources