[英]Update a table from another table
I have got 2 tables "animal_breeds" and "ztmp.ztmp_509810_anims_out". 我有2个表“ animal_breeds”和“ ztmp.ztmp_509810_anims_out”。 In "animals breed" every animal has key and breed name and percentage.
在“动物品种”中,每只动物都有关键的品种名称和百分比。 Few animals might have 2 different breeds with different percentage.
很少有动物会拥有两个不同百分比的不同品种。 Now based on the animals key in "animals_breeds" i want to update "ztmp.ztmp_509810_anims_out"
现在基于“ animals_breeds”中的动物键,我想更新“ ztmp.ztmp_509810_anims_out”
i am using this code which i know is wrong 我正在使用此代码,我知道这是错误的
update ztmp.ztmp_509810_anims_out
set
alt_id1 = ab.breed
,alt_id2 = pcnt
,alt_id3 = ab.breed
,alt_id4 = pcnt
,alt_id5 = ab.breed
,alt_id6 = pcnt
,alt_id7 = ab.breed
,alt_id8 = pcnt
from animal_breeds ab
where ab.soc_code = ztmp_509810_anims_out.soc_code and ab.animals_key = ztmp_509810_anims_out.animals_key
and ab.soc_code = 'AUNDB';
could i use a for loop inside an update statement? 我可以在更新语句中使用for循环吗?
UPDATE ztmp.ztmp_509810_anims_out AS z
SET soc_code = q.soc_code,
animals_key = q.animals_key,
alt_id1 = breeds[1],
alt_id2 = pcnts[1],
alt_id3 = breeds[2],
alt_id4 = pcnts[2]
FROM (SELECT soc_code, animals_key,
array_agg(breed) breeds, array_agg(pcnt) pcnts
FROM animal_breeds
GROUP BY soc_code, animals_key
) q
WHERE z.soc_code = q.soc_code
AND z.animals_key = q.animals_key;
If there can be more than 2 breeds per animals_key
, add breeds[3]
and pcnts[3]
and so on. 如果存在可以是每2个以上品种
animals_key
,添加breeds[3]
和pcnts[3]
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.