SQL Server 2014 update numeric without rounding - sql-server-2014

In my project in SQL Server 2014, I am creating a table on the fly with
select
Region_Code,
'9999999' as [Avg Time to Dispatch in Minutes],
999999999.9999 as [Avg Time to Dispatch in Hours]
from
table1
into
TempTable1
I notice when I look at the design view of this table I created that the 3rd column is of type Numeric(13,4).
I then update this table with real values and get:
region AvgTimeToDispatchInMinutes AvgTimeToDispatchInHours
Maine 393 999999999.9999
I want to get the AvgTimeToDispatchInHours so I do:
UPDATE TempTable1
SET [Avg Time to Dispatch in Hours] = [Avg Time to Dispatch in Minutes] / 60
I am getting 6.00 instead of 6.6 which is what I want.
How can I get 6.6 or the number not being rounded?

You're doing an integer division:
SELECT 393 / 60
results in 6 as you said (because it answers the question: how many times can 60 fit in 393 wholly?).
If you need fractional values, you need to convert at least one of the numbers involved to a fractional type, e.g. decimal - the easiest would be like this:
SELECT 393 / 60.0
which returns 6.55 as expected

Related

SQL query to get the average time spent by user on page

Here is a sample table that I am using,
User_id timestamp action
1 2020-10-01 09:00:00 Opened page
1 2020-10-01 09:10:00 Closed page
2 2020-10-02 04:00:00 Signed up
3 2020-10-02 06:00:00 Opened page
3 2020-10-03 11:00:00 Made a booking
3 2020-10-03 09:30:00 Closed page
need to write a SQL query to find the average time spent by a user on the page.
The expected answer is just a number which represents the average time spent by an average user on the page.
You can’t use SQL to calculate how much time a user spends on different pages of your UI application. You will need to implement this logic on your UI whenever there is an event such as when the user navigates to another page or a button click etc. You capture the timestamps you need on the UI and then make a database call through an SP call or Query through your server side code (such as .Net, Java or Node.js).
Once you have captured the data from the UI you will be able to implement any kind of logic on that data through an SP or a function or something like that in using SQL.
If you use TIMESTAMPDIFF(), and set its argument to SECOND, you can get back the difference of two datetime fields in a record in a manner that can be summed and divided. Documentation:
Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions.
Then use SUM() to sum up these values, and divide by the results of COUNT(). Documentation:
SUM(): Returns the sum of expr. If the return set has no rows, SUM() returns NULL.
COUNT(): Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement.
Your code will then basically look like this. You may need to make some adjustments based on your database setup.
SELECT
SUM(
TIMESTAMPDIFF(SECOND, OrigDateTime, LastDateTime)
) / (select COUNT(id) FROM yourTable)
AS average
FROM yourTable;
This, of course, follows our standard formula for calculating an average:
sum(differences) / count(differences)

How to get the difference of dates or TAT in ssrs

I want to get the Turn Around Time(TAT) of dates. for example:
I have a createddatetime 2016-11-02 06:21:34.000 and endeddatetime 2016-11-02 22:00:00.000. I want to get the difference of two dates by 2 decimal places. Anyone can help for the SSRS expression needed to perform this?
Result for the above diff is 0.67
TIA!
With number formatting set to Number with 2 decimal places, this expression gives you the same result as your SQL statement:
=Round(DateDiff(DateInterval.Second,Fields!FirstDate.Value,Fields!SecondDate.Value) /60 / 60, 0) / 24
You need to calculate the number of seconds and round this as an hour value to emulate the behaviour of SQL's DATEDIFF function as the .NET version only considers complete units when comparing dates. See this question for further details of this: SQL Server DateDiff Vs .Net DateDiff.
If you just used:
=DateDiff(DateInterval.Day,Fields!FirstDate.Value,Fields!SecondDate.Value)
then you'll get a result of 0.00 as there are no complete days between these dates, rather than the 0.65 you get from the SQL statement.
Similarly, if you try:
=DateDiff(DateInterval.Hour,Fields!FirstDate.Value,Fields!SecondDate.Value) / 24
you'll get a result of 0.63, as the number of complete hours between your dates is 15 and 15 / 24 = 0.625.

mysql convert bigint to datetime

The CreateDateTime column in a table is in the format bigint(20). For example it looks like: 131037078373067074. I didn't create this table, it is passed on to me.
Using the example here Convert BigInt timestamp to a real Date with row aggregation and operations in mySQL, I have tried dividing CreateDateTime by POW(10,8) or POW(10,9) .
SELECT FROM_UNIXTIME(CreateDateTime/POW(10,8)) AS due_date
FROM images;
results look like '2011-07-11 02:53:03.730671'.
SELECT FROM_UNIXTIME(CreateDateTime/POW(10,9)) AS due_date
FROM images;
results look like '1974-02-25 09:11:18.373067'.
I am expecting a date in 2016. However dividing CreateDateTime by POW(10,7) gives null.
What should I do?
I am expecting a date in 2016.
Dividing by 89000000 gives a date in 2016
(To discover that I converted a date in the middle of 2016 to seconds since unix epoch and divided your number by that).
What should I do?
If you have some way to get the real datetime (like from an existing and known working user interface) you can probably reverse engineer the formula. Take several samples and keep track of the number in CreateDateTime and the correct date time. The number may represent microseconds or nanoseconds since a different epoch. Unix uses 1970-01-01 UTC, Excel uses Jan 0, 1900 (no, not Jan 1 but Jan 1 - 24 hours), NTP uses Jan 1 1900, IBM BIOS (and ZIP) uses Jan 1, 1980.
The number of "fractional seconds" in one second may be a multiple of 60 instead of 10.
Use the data you gather from the user interface to solve for
(CreateDateTime + a) / b = UnixSecondsSince1970_01_01
OR
(CreateDateTime / b) + a = UnixSecondsSince1970_01_01
where "a" is the offset needed to adjust for non-unix epoch and "b" is the number of units needed to add up to one second in the "CreateDateTime" representation.
Others epoch choices referenced here:
https://en.wikipedia.org/wiki/Epoch_(computing)#Notable_epoch_dates_in_computing
( 131037078373067074 / 10000000000 + ( 24 * 60 * 60 * 17000 ) )
Also gives a date in 2016

Prune mysql table - averaging records

I have a MySQL table which stores real-time data from different devices. Data is recorded about every 20 seconds.
The table looks like this:
report_dt device value1 value2
2015-10-16 10:32:15 solar 34.4 67.8
2015-10-16 10:32:15 grid 56.9 23.5
2015-10-16 10:32:35 solar 45.6 34.3
Queries to get the recorded values per device are pretty CPU consuming. I have (report_dt,device) as primary key. Besides, after a few days I do not need the 20 second data anymore, but just the 10 minute average.
So either the same table setup or a table per device would be satisfactory, with this contents:
report_dt device value1
2015-10-16 10:00:00 solar avg(value1 over 10 mins)
2015-10-16 10:10:10 grid avg(value1 over 10 mins)
2015-10-16 10:20:20 solar avg(value1 over 10 mins)
The idea is to run the pruning action once every 24 hours.
The reason is that data containing averages must be retrieved fast. And because the data in a 20 second interval is extremely fluctuating, I must use averaging or the data is difficult to assess.
I could do this in an application. Retrieve the average values for 10 minutes at each 10 minute interval and write it back to a different table or different tables, one for each device.
But would something also be possible with a database function?
You can do this by Events in mysql. Suppose i have 2 tables in mysql. Table_1 store the data continiously per second or miunte as your application generate. Table_2 is your main table which contains the 10 min avg data. Now you need to create a stored procedure which calls once in 10 minutes (this can be done by Events or CRON in linux ). So whats contains the stored procedure ? These steps perform in Stored Procedure
BEGIN
SELECT avg(value) of last 10 min from Table_1
INSERT into Table_2 the avg record.
DELETE avg(value) of last 10 min from Table_1
END
Caution- I am not developing mysql code, i am just show the approach

get average interarrival time for service requests by timestamp

I have partly the following MySQL schema
ServiceRequests
----------
id int
RequestDateTime datetime
This is what a typical collection of records might look like.
1 | 2009-10-11 14:34:22
2 | 2009-10-11 14:34:56
3 | 2009-10-11 14:35:01
In this case the average request time is (34+5)/2 = 19.5 seconds, being
14:34:22 ---> (34 seconds) ----> 14:34:56 ------> (5 seconds) -----> 14:35:01
Basically I need to work out the difference in time between consecutive records, sum that up and divide by the number of records.
The closest thing I can think of is to convert the timestamp to epoch time and start there. I can add a field to the table to precalculate the epoch time if necessary.
How do I determine 19.5 using a sql statement(s)?
You don't really need to know the time difference of each record to get the average. You have x data points ranging from some point t0 to t1. Notice that the the last time - first time is also 39 sec. (max-min)/(count-1) should work for you
select max(RequestDateTime)-min(RequestDateTime) / (count(id)-1) from ServiceRequests;
Note: This will not work if the table is empty, due to a divide by zero.
Note2: Different databases handle subtraction of dates differently so you may need to turn that difference into seconds.
Hint: maybe using TIMEDIFF(expr1,expr2) and/or TIME_TO_SEC(expr3)