计算平均数,添加日期,并将查询保存到新的表中

问题描述 投票:0回答:1

我有一个名为pt_products的表,其字段为。

  `id` int(6) unsigned NOT NULL,
  `ean` bigint(13) unsigned NOT NULL,
  `merchant` varchar(64) NOT NULL,
  `price` decimal(10,2)NOT NULL,
  PRIMARY KEY (`id`)

表上的条目示例。

INSERT INTO `pt_products` (`id`, `ean`, `merchant`, `price`) VALUES
 ('1', '884116311874', 'Amazon', '10000.00'),
  ('2', '884116311874', 'BestBuy', '10999.00'),
('3','884116321378', 'CyberPuerta', '14789.00'),
 ('4', '884116311875', 'Amazon', '10999.00'),
  ('5', '884116311875', 'BestBuy', '10000.00');

我想用pt_products上的数据创建一个新的表叫 "graph",它有以下字段:

-ean代码.-每个条目的'价格'字段的平均值,这些条目共享相同的'ean'-条目被添加到新表中的日期,自动添加。

我试过的方法 (演示):

SELECT AVG(price)
FROM pt_products
GROUP BY ean;

我得到了。

AVG(price)
929.500000
3697.333333
3834.000000
9999.990000
10499.500000
10499.500000
14789.000000

这样我就得到了具有相同ean的条目的平均价格 但我看不到与平均价格相对应的 "ean 当然我也没有把它存储到一个新的表中,包括发起查询的日期。

这样做的目的是为了获得每个ean和每天的价格平均值,以便从数据中制作一个显示价格作为时间函数的图表,所以我需要检索平均值的日期。

谢谢你

mysql date subquery average
1个回答
2
投票

只需添加 ean 栏目到 select 子句。

select ean, avg(price) avg_price
from pt_products
group by ean

你可以直接从查询结果中创建一个新的表,但这不能让你微调表的选项(主键、索引......)。

create table graph as
select ean, avg(price) avg_price, now() created_at
from pt_products
group by ean

但这不能让你对表的选项进行微调(主键、索引...)。最好的办法是先创建表,然后再 insert 到它 - 你可以设置一个默认为当前时间点的时间戳。

create table graph (
    id int primary key auto_increment,
    ean bigint(13) unsigned not null,
    avg_price decimal(10,2) not null,
    created_at timestamp default current_timestamp
);

insert into graph(ean, avg_price)
select ean, avg(price) avg_price
from pt_products
group by ean;
© www.soinside.com 2019 - 2024. All rights reserved.