MySQL average value of each hour for the last 30 days - mysql

I have a table, that is updated every minute and I need to calculate the average value of each hour, for the values of the last 30 days.
Timestamp | SB1_AC_GES_DIFF
2020-07-14 15:13:04 30
2020-07-14 15:12:07 27
... ...
I want to save the results in a second table named avgTable like this
Timestamp | AVG_SB1
15:00 29
16:00 32
... ...
It would be perfect if the table could update itself once a day, maybe when it's 12 o'clock and the the date part for the day changes.

You can try:
INSERT INTO avg_table
SELECT Date_format(Timestamp, "%h:00:00") AS HourlyTimeStamp,
Avg(sb1_ac_ges_diff) AS "AVG_SB1"
FROM table
WHERE Timestamp between DATEADD(DAY, -30, GETDATE()) AND GETDATE()
GROUP BY 1
Assuming that you want the average rolling average, agnostic of the day.

You can just use the hour() function:
select hour(timestamp) as hh, avg(sb1_ac_ges_diff)
from t
group by hh;
You can convert this to a string or time if you want, but that does not seem useful to me.
If you actually want the hour for each day, then:
select date(timestamp) as dd, hour(timestamp) as hh, avg(sb1_ac_ges_diff)
from t
group by dd, hh;

Related

Get average day or week values

I have statistical data like this:
time val1
1424166578 51
1424166877 55
1424167178 57
1424167477 57
time is a unix timestamp. There is one record every 5 minutes excluding nights and sundays. This continues over several weeks.
Now I want to get these values for an average day and an average week. The result should include values for every 5 minutes like normal but for average past days or weeks.
The result should look like this:
time val1
0 43.423
300 46.635
600 51.887
...
So time could be a timestamp with relative time since day or week start. Perhaps it is better to use DATETIME... not sure.
If I use GROUP BY FROM_UNIXTIME(time, '%Y%m%d') for example I get one value for the whole day. But I want all average values for all days.
You seem to be interested in grouping dates by five minute intervals instead of dates. This is fairly straightforward:
SELECT
HOUR(FROM_UNIXTIME(time)) AS HH,
(MINUTE(FROM_UNIXTIME(time)) DIV 5) * 5 AS MM,
AVG(val1) AS VAL
FROM your_table
WHERE time > UNIX_TIMESTAMP(CURRENT_TIMESTAMP - INTERVAL 7 DAY)
GROUP BY HH, MM
The following result will explain how date is clamped:
time FROM_UNIXTIME(time) HH MM
1424166578 2015-02-17 14:49:38 14 45
1424166877 2015-02-17 14:54:37 14 50
1424167178 2015-02-17 14:59:38 14 55
1424167477 2015-02-17 15:04:37 15 00
I would approach this as:
select date(from_unixtime(time)) as day, avg(val)
from table t
group by date(from_unixtime(time))
order by day;
Although you can use the format argument, I think of that more for converting the value to a string than to a date/time.

Mysql: select timestamps between 22th of january and 3rd of february, any year

I need to compare sales in a period of days, across several years in my databases.
So I need to select rows with a timestamp that is in the range 22th january to 3rd february. The year can be anything.
How to do this?
example table sales:
timestamp sales_amount
2012-01-22 16:28:01 78
2012-10-11 16:28:06 90
2014-02-01 16:28:06 27
Select should get row 1 and 3, and exclude row 2 since its not between the specified days.
Try this
SELECT * FROM the_table WHERE DAYOFYEAR(`the_date_column`) BETWEEN 9 AND 34
This does not always work, but works for your required date range, because DAYOFYEAR of any date in that range is always fixed regardless of year.
As a general solution, you can play the trick, that you set the year to a specific one. For example:
select * from t
where str_to_date(date_format(timestamp, '1970-%m-%d %H:%i:%s'), '%Y-%m-%d %H:%i:%s')
between '1970-01-22 00:00:00' and '1970-02-03 23:59:59';

MySQL: need to calculate the last Friday of a month

I'm trying to solve a task: I have a table containing information about ships' battles. Battle is made of name and date. The problem is to get the last friday of the month when the battle occurred.
WITH num(n) AS(
SELECT 0
UNION ALL
SELECT n+1 FROM num
WHERE n < 31),
dat AS (
SELECT DATEADD(dd, n, CAST(battles.date AS DATE)) AS day,
dateadd(dd, 0, cast(battles.date as date)) as fight,
name FROM num,battles)
SELECT name, fight, max(day) FROM dat WHERE DATENAME(dw, day) = 'friday'
I thought there must be a maximum of date or something, but my code is wrong.
The result should look like this:
Please, help!!
P.S. DATE_FORMAT is not available
Possible problem: as spencer7593 noticed - and as I should have done and didn't - your original query is not MySQL at all. If you're porting a query that's OK. Otherwise this answer will not be helpful, as it makes use of MySQL functions.
The day you want is number 4 (0 being Sunday in MySQL).
So you want the last day of the month if the last day of the month is a 4; if the day of the month is a 5 you want a date which is 1 day earlier; if the day of the month is a 3 you want a date which is 1 day later, but that's impossible (the month ends), so you really need a date six days earlier.
This means that if the daynumber difference is negative, you want it modulo seven.
You can then build this expression (#DATE is your date; I use a fake date for testing)
SET #DATE='2015-02-18';
DATE_SUB(LAST_DAY(#DATE), INTERVAL ((WEEKDAY(LAST_DAY(#DATE))+7-4))%7 DAY);
It takes the last day of the month (LASTDAY(#DATE)), then it computes its weekday, getting a number from 0 to 6. Adds seven to ensure positivity after subtracting; then subtract the desired daynumber, in this case 4 for Friday.
The result, modulo seven, is the difference (always positive) from the last day's daynumber to the wanted daynumber. Since DATE_SUB(date, 0) returns the argument date, we needn't use IF.
SET #DATE='1962-10-20';
SELECT DATE_SUB(LAST_DAY(#DATE), INTERVAL ((WEEKDAY(LAST_DAY(#DATE))+7-4))%7 DAY) AS friday;
+------------+
| friday |
+------------+
| 1962-10-26 |
+------------+
Your query then would become something like:
SELECT `name`, `date`,
DATE_SUB(LAST_DAY(`date`),
INTERVAL ((WEEKDAY(LAST_DAY(`date`))+7-4))%7 DAY) AS friday
FROM battles;

MySQL time diff grouped by day

I have a table from which I'm trying to extracted summed timediff information grouped by days. I don't really know if this is possible
Table columns: mode_type, start_time.
A record exists in this table for each time an employee starts or stops a timer. mode_type = 1 for start, mode_type = 0 for stop.
I'd like to return a sum of the seconds used for each day in the last 30 days.
E.g:
date, seconds_used
02/04/2014, 25
03/04/2014, 12415
04/04/2014, 925
Currently I can return a list of seconds used per mode_type and date but this required later calc in PHP.
SELECT
mode_type,
Sum(Unix_Timestamp(start_time)) AS time,
start_time
FROM
activations
WHERE
start_time < Date(Now() + INTERVAL 1 MONTH)
GROUP BY
mode_type, Day(start_time)
ORDER BY
start_time
I'm stuck... is this possible or do I need to do revert to calculating the diff in PHP post request?
Thanks in advance.
Can you try with this:
SELECT DATE(start_time) AS startdate, TIME_TO_SEC(TIMEDIFF(NOW(),start_time)) AS secs
FROM activations
GROUP BY
startdate

How to Subtract Days in MySQL

How can I subtract time in MySQL? For example, today is 16 March; I want to subtract 15 days to reach 1 March. Are there any methods that can be used to subtract 15 days from the current date?
SELECT DATE(NOW()-INTERVAL 15 DAY)
For a list of units see http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add
Not entirely related to this question but is related to the title:
SELECT SUBTIME("10:24:21", "5"); -- subtracts 5 seconds. (returns "10:24:16")
SELECT SUBTIME("10:24:21", "01:00:00"); -- subtracts one hour. (returns "09:24:21")
Documentation: MySQL SUBTIME function
Use:
SELECT NOW() - INTERVAL 15 DAY
to keep the datetime precision.
You can use this :
SELECT DATE(NOW()-INTERVAL 15 DAY);
for when you want to subtract the number of days.
In order to subtract the time instead, say 15 minutes, the following should work:
SELECT(DATE_SUB(NOW(), INTERVAL '15:0' MINUTE_SECOND));
Adding the reference link again :- https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add.
Yes its possible using date function in Mysql
select distinct
lastname,
changedat, date_add(changedat, interval -15 day) as newdate
from employee_audit;
lastname and changedat is field name and employee_audit is table name.
I have subtract 15 days from my date - check image please. thanks