Calculate average date difference between records in MS Access - ms-access

I have a list on when items have been handed out. The table has the following structure:
primary key - autonumber itemname
itemid - number
datehandedout - date/time
I want to calculate the average length of time between when one object is given out and the next one is given out. There will be a number of different items for which the average time between handouts needs to be listed for.
So something like (pseudocode):
average( [thisrecord]![datehandedout] - [lastrecord]![datehandedout] )
Any help will be much appreciated.

This is a very slow query:
SELECT Avg(DateDiff("h",[datehandedout],(
SELECT TOP 1 datehandedout
FROM tbl tx
WHERE tx.datehandedout > t.datehandedout))) AS Difference
FROM tbl AS t
Add another Where statement to limit the number of records returned when you test, for example:
WHERE Year([datehandedout])=2010

Related

mysql - calculating columns(2 columns with numbers) based on another group of column(text)

Hi I would like to find a query for the below, I am trying to calculate data between two columns however based on another column which needs to be a selected group of the same values
Unfiltered
Start Time________Disconnect Time______Signalling IP
12:59:00.3________13:26:03.3___________1.1.1.1
10:59:00.3________11:03:03.3___________2.2.2.2
19:59:00.3________20:02:03.3___________1.1.1.1
Filtered
Start Time________Disconnect Time______Signalling IP
12:59:00.3________13:26:03.3___________1.1.1.1
19:59:00.3________20:02:03.3___________1.1.1.1
If you see the table above, I want the selected IP only which is 1.1.1.1, and then from there, calculate the total duration of time from the Start Time and Disconnect Time for that Egress IP.
So column 3 has multiple values, however I need to select the same value, then from there calculate the sum of column 1 and 2 based on column 3.
Please let me know if you have anything in mind, as I have tried multiple queries but can't get the correct one
to calculate difference between to times.
you can use time_to_sec to convert each time value to seconds
and subtract start time from end time to get time period in seconds.
you cat turn it back to time format with SEC_TO_TIME
example
select
column3,
SEC_TO_TIME(sum(TIME_TO_SEC(column2) - TIME_TO_SEC(column1))
from
table
group by column3

mysql selecting records for every n hour

I have around 200,000 records and each record has DATETIME field. I have been trying to select records by every n hours using the DATETIME field. For example if n = 1; 1 record is selected for every 1 hour. I haven't been able to find many examples online.
Table: Product
Fields: id, name, description, lastSoldOn
Well, you can convert the date/time to seconds and use arithmetic to select one value from each n-hour period:
select min(datetimecol)
from t
group by floor(to_seconds(datetimecol) / (3600 * $n));
If you need the complete record, you can use join or exists to match back to the original table.

how can I calculate the SUM in 4days buckets over all dates

I have a MySQL DB where one column is the DATE and the other column is the SIGNAL. Now I would like to calculate the SUM over Signal for 4 days each.
f.e.
SUM(signal over DATE1,DATE2,DATE3,DATE4)
SUM(signal over DATE5,DATE6,DATE7,DATE8)
...
whereas Date_N = successor of DATE_N-1 but need not to be the day before
Moreless the algo should be variable in the days group. 4 ist just an example.
Can anyone here give me an advice how to perform this in MySQL?
I have found this here group by with count, maybe this could be helpful for my issue?
Thanks
Edit: One important note: My date ranges have gaps in it. you see this in the picture below, in the column count(DISTINCT(TradeDate)). It should be always 4 when I have no gaps. But I DO have gaps. But when I sort the date descending, I would like to group the dates together always 4 days, f.e. Group1: 2017-08-22 + 2017-08-21 + 2017-08-20 + 2017-08-19, Group2: 2017-08-18 + 2017-08-17+2017-08-15+2017-08-14, ...
maybe I could map the decending dateranges into a decending integer autoincrement number, then I would have a number without gaps. number1="2017-08-17" number2="2017-08-15" and so on ..
Edit2:
As I see the result from my table with this Query: I might I have double entries for one and the same date. How Can I distinct this date-doubles into only one reprensentative?
SELECT SUM(CondN1),count(id),count(DISTINCT(TradeDate)),min(TradeDate),max(TradeDate) ,min(TO_DAYS(DATE(TradeDate))),id FROM marketstat where Stockplace like '%' GROUP BY TO_DAYS(DATE(TradeDate)) DIV 4 order by TO_DAYS(DATE(TradeDate))
SUM() is a grouping function, so you need to GROUP BY something. That something should change only every four days. Let's start by grouping by one day:
SELECT SUM(signal)
FROM tableName
GROUP BY date
date should really be of type DATE, like you mentioned, not DATETIME or anything else. You could use DATE(date) to convert other date types to dates. Now we need to group by four dates:
SELECT SUM(signal)
FROM tableName
GROUP BY TO_DAYS(date) DIV 4
Note that this will create an arbitary group of four days, if you want control over that you can add a term like this:
SELECT SUM(signal)
FROM tableName
GROUP BY (TO_DAYS(date)+2) DIV 4
In the meantime and with help of KIKO I have found the solution:
I make a temp table with
CREATE TEMPORARY TABLE if not EXISTS tradedatemaptmp (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY) SELECT Tradedate AS Tradedate, CondN1, CondN2 FROM marketstat WHERE marketstat.Stockplace like 'US' GROUP BY TradeDate ORDER BY TradeDate asc;
and use instead the originate tradedate the now created id in the temp table. So I could manage that - even when I have gaps in the tradedate range, the id in the tmp table has no gaps. And with this I can DIV 4 and get the always the corresponding 4 dates together.

Select average value X of SQL table column while not grouping by X

For the purposes of my question, I have a database in a MySQL server with info on many taxi rides (it is comprised of two tables, history_trips and trip_info).
In history_trips, each row's useful data is comprised of a unique alphanumeric ID, ride_id, the name of the rider, rider, and the time the ride ended, finishTime as a Y-m-d string.
In trip_info, each row's useful data similarly contains ride_id and rider, but also contains an integer, value (calculated in the back end from other data).
What I need to do is create a query that can find the average of all the maximum 'values' from all riders in a given time period. The riders included in this average are only considered if they completed less than X (let's say 3) rides within the aforementioned time period.
So far, I have a query that creates a grouped table containing the name of the rider, the finishTime of their highest 'value' ride, the value of said ride, and the number of rides, num_rides, they have taken in that time period. The AVG(b.value) column, however, gives me the same values as b.value, which is unexpected. I would like to find some way to return the average of the b.value column.
SELECT a.rider, a.finishTime, b.value, AVG(b.value), COUNT(a.rider) as num_rides
FROM history_trips as a, trip_info as b
WHERE a.finishTime > 'arbitrary_start_date_str' and a.ride_id = b.ride_id
and b.value = (SELECT MAX(value)
from trip_info where rider = b.rider and ride_id = b.ride_id)
GROUP BY a.rider
HAVING COUNT(a.rider) < 3
I am a novice in SQL but have read on some other forums that when using the AVG function on a value you must also GROUP BY that value. I was wondering if there is a way around that or if I am thinking of this problem incorrectly. Thanks in advance for any advice / solutions you might have!
The following worked for me:
SELECT AVG(ridergroups.maxvalues) avgmaxvalues FROM
(SELECT MAX(trip_info.value) maxvalues FROM trip_info
INNER JOIN history_trips
ON trip_info.rideid = history_trips.ride_id
WHERE history_trips.finishTime > '2010-06-20'
GROUP BY trip_info.rider
HAVING COUNT(trip_info.rider) < 3) ridergroups;
The subquery groups the maximum values by rider after filtering by date and rider count. The containing query calculates the average of the maximum values.

Aggregating/Grouping a set of rows/records in MySQL

I have a table say "sample" which saves a new record each five minutes.
Users might ask for data collected for a specific sampling interval of say 10 min or 30 min or an hour.
Since I have a record every five minutes, when a user asks for data with a hour sample interval, I will have to club/group every 12 (60/5) records in to one record (already sorted based on the time-stamp), and the criteria could be either min/max/avg/last value.
I was trying to do this in Java once I fetch all the records, and am seeing pretty bad performance as I have to iterate through the collection multiple times, I have read of other alternatives like jAgg and lambdaj, but wanted to check if that's possible in SQL (MySQL) itself.
The sampling interval is dynamic and the aggregation function (min/max/avg/last) too is user provided.
Any pointers ?
You can do this in SQL, but you have to carefully construct the statement. Here is an example by hour for all four aggregations:
select min(datetime) as datetime,
min(val) as minval, max(val) as maxval, avg(val) as avgval,
substring_index(group_concat(val order by datetime desc), ',', 1) as lastval
from table t
group by floor(to_seconds(datetime) / (60*60));