Aggregate and calculate total minutes for set of records as productivity - sql

I have a table that lists activity for people and start / end timed for activity.
How do I get total amount of records for each person?
SELECT NAME,
--sum(startDT- endDT) AS minutes -- stuck here
FROM TABLE1
GROUP BY NAME

You're subtracting end time from start time, which will produce a negative value - try flipping those around (subtract start time from end time). The following will give you the number of records and the total elapsed time for each NAME:
SELECT NAME,
COUNT(*) AS "Records for NAME",
TO_CHAR(NUMTODSINTERVAL(SUM(END_DATE_TIME - START_DATE_TIME), 'DAY')) AS MINUTES
FROM TABLE1
GROUP BY NAME
SQLFiddle here
Share and enjoy.

Assuming that startDT and endDT are both of type date, you were really close. Subtracting two dates gives a difference in days. Multiply by 24 to get a difference in hours and again by 60 to get minutes
SELECT NAME,
sum(endDT - startDT)*24*60 AS minutes -- stuck here
FROM TABLE1
GROUP BY NAME
Assuming that your differences aren't always an exactly even number of minutes, you'll either get a non-integer result (e.g. 12.5 for 12 minutes 30 seconds) here or you'll want to either round or trunc the sum to get an integer number of minutes.

Related

I have a sum of difference between dates in a Sql table. How do I calculate its average in days, hours, minutes?

I have a table with a start time and an end time (datetime, example: 2021-07-09 17:12:00) in each row.
When I calculate the sum of all differences between end time and start time by this SQL query:
SELECT
TIME(SUM(TIMEDIFF(`end_time`, `start_time`))) AS TimeDiff
FROM
my_table
I get a result expressed in hours, minutes, seconds (example: 00:02:00)
Now I need to calculate the average time expressed in hours, minutes, seconds of this sum.
It means:
SELECT
TIME(SUM(TIMEDIFF(`end_time`, `start_time`))) AS TimeDiff
FROM
my_table
TimeDiff/number of rows (expressed in hours, minutes, seconds)
Can you help me? Really thanks
Going out on a limb and guessing you're using MySQL due to the TIMEDIFF function.. Always state what DB you use; SQL is a standard, not a product
You asked about converting times to seconds and back, it probably looks like:
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(TIMEDIFF(end_time, start_time)))) FROM ...

Time looping an average

I have a table with 17,000 records that is ordered by time spaced in 15 minute intervals. The time values loop back onto themselves every 24 hours, so for example, I could have 100 records that are all at 1 AM, just on different days. I want to create a 'average day' by taking those 100 records at 1 am and finding the average of them for the averaged 1 am.
I don't know how to format the table to make it show up nicely here.
I'm assuming you want to calculate the average value per time interval regardless of the day in a query. You could use this SQL to group your table by Time interval only (assuming that it's separate from the date field), and average whichever fields you want to average. Do not select or group by the date field, just select and group by the time field.
SELECT TimeField
, AVG([Field1ToAverage])
, AVG([Field2ToAverage])
FROM MyTable
GROUP BY TimeField;
If the date and time fields are stored together in the same column, you will have to extract the time only:
SELECT TimeValue([DateTimeField])
, AVG([Field1ToAverage])
, AVG([Field2ToAverage])
FROM MyTable
GROUP BY TimeValue([DateTimeField]);

In SQL, how can I count rows grouping into certain intervals, if I only know the length of those intervals?

Let's say that my first column is time. What I want is to be able to count the rows grouping them by an arbitrary time range, for instance: by day, by hour, by 20 minutes intervals, by 15 seconds etc.
Convert the timestamp into some appropriate number (here: number of seconds since the Unix epoch), then do an integer division by the number of seconds (which implicitly rounds down):
SELECT ...
GROUP BY strftime('%s', MyDate) / 15 -- or 20*60 etc.

Efficient PostgreSQL Query for Mins and Maxis withing equal intervals in a time period

I am using Postgres v9.2.6.
Have a system with lots of devices that take measurements. These measurements are stored in
table with three fields.
device_id
measurement (Indexed)
time (Indexed)
There could be 10 Million measurements in a single year. Most of the time the user is only interested in 100 min max pairs within equal interval for a certain period, for example in last 24 hours or in last 53 weeks. To get these 100 mins and maxs the period is divided into 100 equal intervals. From each interval min and max is extracted. Would you recommend the most efficient approach to query the data? So far I have tried the following query:
WITH periods AS (
SELECT time.start AS st, time.start + (interval '1 year' / 100) AS en FROM generate_series(now() - interval '1 year', now(), interval '1 year' / 100) AS time(start)
)
SELECT * FROM sample_data
JOIN periods
ON created_at BETWEEN periods.st AND periods.en AND
customer_id = 23
WHERE
sample_data.id = (SELECT id FROM sample_data WHERE created_at BETWEEN periods.st AND periods.en ORDER BY sample ASC LIMIT 1)
This test approach took over a minute for 1 million points on MacBook Pro.
Thanks...
Sorry about that. It was actually my question and looks like the author of this post caught cold so I ca not ask him to edit it. I've posted "more good" question here - Slow PostgreSQL Query for Mins and Maxs within equal intervals in a time period. Could you please close this question?

SQL Average Count of records over n months

I'm trying to do something that seems simple but I can't figure out how to write it up in SQL. I have a table of records including a field containing a date. I would like to get an overall average number of records per month using that date field. This is not an AVG that is grouped by month, but an overall average.
So if my table contains quotes, and there is 7 different months of data in that table, I'm looking to get:
Total number of records / n months of data
Now I need to get this into SQL.
You can try to use the DateDiff function on the Min and Max of your date field.
DateDiff function:
DateDiff ( interval, date1, date2, [firstdayofweek], [firstweekofyear])
Example:
SELECT count(*) / DateDiff('m', Min(date), Max(date))
FROM ...
How does this work?
count will give you the total number of rows (# of quotes in your quotes table), and DateDiff will give you the total number of months between the first and last date.