I think this should do it, but I haven't tested it.
The basic procedure is to create a temporary table which contains the summed values for those entities you care about, then update the proper attribute rows with those values.
Note that php is not necessary here, only SQL. You may of course want to use php to issue the query.
UPDATE
catalog_product_entity_decimal,
(SELECT entity_id, SUM(value) AS summedvalue FROM catalog_product_entity_decimal as cped
WHERE attribute_id IN (145, 146)
AND EXISTS (SELECT 1 FROM catalog_product_entity_decimal WHERE entity_id=cped.entity_id and attribute_id=141)
GROUP BY entity_id
) AS sums
SET catalog_product_entity_decimal.value = sums.summedvalue
WHERE catalog_product_entity_decimal.entity_id=sums.entity_id
AND catalog_product_entity_decimal.attribute_id=141;
This builds an intermediate table sums that looks like this (based on data in table screenshot):
entity_id | summedvalue
1 | 12
2 | 0
If there's an entity_id without a row with an attribute_id=141, that entity_id won't have a row in this sums table--this is ensured by the EXISTS() condition.
Then we update the catalog_product_entity_decimal table (I'll abbreviate it CPED) by joining it with sums on the entity_id.
CPED.entity_id | CPED.attribute_id | sums.entity_id | sums.summedvalue
1 | 145 | 1 | 12
2 | 145 | 2 | 0
SET CPED.value = sums.summedvalue does the actual setting.