我有这个查询,该查询的结构更适合mysql
update metrics m join
(select repnumber, material, item, color, sum(m2.velocity)/count(*) as avg_velocity
from metrics m2
group by repnumber, material, item, color
) m2
using (repnumber, material, item, color)
set m.repvolocity = m2.avg_velocity;
是否可以更改它以使其适用于db2?
答案 0 :(得分:3)
在DB2(和大多数其他数据库)中,您将使用相关子查询:
update metrics m
set repvolocity = (select avg(m2.velocity)
from materials m2
where m2.repnumber = m.repnumber and m2.material = m.material and m2.item = m.item and m2.color = m.color
);
我应该注意,DB2还使动态计算值变得容易:
select m.*,
avg(m.velocity) over (partition by repnumber, material, item, color) as repvelocity
from materials;
使用窗口功能,您可能会发现不需要实际存储该值。我要补充一点,MySQL 8+也具有此功能。