简体   繁体   中英

How to set value of table1.column1 to an average of table2.column2

I've looked all over and I can't seem to find a clear solution. Sorry if I missed it.

My Problem: I have data that is accumulated hourly and placed in table1 I want table2.metric_ to contain an average of table1.metric_ for that day.

table1 : record_key_, id_, metric_, date_

table2 : record_key_, id_, metric_, date_

to get the list of records for the day I use: SELECT * FROM table1 t WHERE t.date_ >= DATE_SUB(NOW(),INTERVAL 1 DAY) WHERE t.id_='id1';

what does the INSERT query for table2 look like so that table2.metric_ is an average of the values from the table1.metric_ column for all records of id1 in table1 returned by the previous SELECT statement?

insert into table2 SELECT avg(total) FROM (SELECT count(*) as Total FROM table1 t WHERE t.col= DATE_SUB(NOW(),INTERVAL 1 DAY) group by colname) as a
INSERT INTO table2 metric_
       SELECT AVG(t.metric_) FROM table1 t WHERE t.date_ >= DATE_SUB(NOW(),INTERVAL 1 DAY) WHERE t.id_='id1');

should be the solution You can add the date_ formatted as you like in the SELECT statement

Did not test the query as I don't have MySQL test databases.

Source: INSERT-SELECT in MySQL reference

(I can not comment on accepted answer, but i am quite sure it is wrong? It counts how much entries there are and calculates the average to (how many hours does a day have? )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM