我希望我能将这3个更新查询烘焙成一个高效漂亮的查询来更新我的价格表。我知道你们中的一些人可能想知道为什么我要做这个更新,而不仅仅是在我需要数据的时候做我的平均值,你可以继续想。
查询#1用12个月内价格组的平均价格更新价格表。
查询#2用6个月内价格组的平均价格更新价格表。
查询#3用3个月内价格组的平均价格更新价格表。
SET
@p12 = '2017-12-01',
@p6 = '2018-06-01',
@p3 = '2018-09-01',
@p1 = '2019-12-01';
/* AVG PRICE 12 MONTHS */
UPDATE
prices
JOIN product ON
product.id = prices.product_id
JOIN(
SELECT
pricegroup,
AVG( price ) as avg_price
FROM
price_temp
WHERE
sales_date BETWEEN @p12 AND @p1
GROUP BY
pricegroup
) as a ON
a.pricegroup = product.pricegroup
SET
prices.price_12 = a.avg_price
WHERE
prices.`date` = @p1;
/* AVG PRICE 6 MONTHS */
UPDATE
prices
JOIN product ON
product.id = prices.product_id
JOIN(
SELECT
pricegroup,
AVG( price ) as avg_price
FROM
price_temp
WHERE
sales_date BETWEEN @p6 AND @p1
GROUP BY
pricegroup
) as a ON
a.pricegroup = product.pricegroup
SET
prices.price_6 = a.avg_price
WHERE
prices.`date` = @p1;
/* AVG PRICE 3 MONTHS */
UPDATE
prices
JOIN product ON
product.id = prices.product_id
JOIN(
SELECT
pricegroup,
AVG( price ) as avg_price
FROM
price_temp
WHERE
sales_date BETWEEN @p3 AND @p1
GROUP BY
pricegroup
) as a ON
a.pricegroup = product.pricegroup
SET
prices.price_3 = a.avg_price
WHERE
prices.`date` = @p1;
----价格表----
| id | product_id | date | price | price_3 | price_6 | price_12 |
----产品表----
| id | pricegroup |
----价格和温度表----
| pricegroup | sales_date | price |
1条答案
按热度按时间yqkkidmi1#
所以在看了案例之后,我重新创建了查询,并在avg中使用了案例