我有一个名为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”的每个条目的“price”字段的平均值-当条目被添加到新表中时的日期,自动添加。
我所尝试的(演示):
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和每天的平均价格,以便从数据显示价格作为时间的函数的图表,所以我需要检索的平均日期。
谢谢
只需将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
但这不能使您微调表选项(主键,索引。。。)。 最好先创建表,然后插入
到其中--并且可以设置默认为当前时间点的时间戳:
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 pt_products_agg(ean, avg_price)
select ean, avg(price) avg_price
from pt_products
group by ean;