简体   繁体   中英

Update column within CASE statement with results of a subquery postgres

I need to update a column based on the results of a subquery. If the subquery returns results for that column then the columns must be updated, is the query returns no results for that column then I need to update with 0.

I do not know where to place the subquery and how to combine it with the CASE statement. This is what I thought but the syntax is not correct. Can anybody help please?

(SELECT datazones.ogc_fid, count(*) as total 
FROM suppliersnew suppliers, datazone_report_resupply datazones
WHERE St_contains(datazones.geom, suppliers.geometry) AND (suppliers.status = 'Under construction' OR
suppliers.status = 'Unknown' OR suppliers.status = 'Operational') GROUP by datazones.ogc_fid ORDER BY total ASC) sources 

UPDATE datazone_report_resupply
SET es_actual =
CASE 
    WHEN datazone_report_resupply.ogc_fid = sources.ogc_fid THEN sources.total
    ELSE 0
END

The query is a little hard to follow, because the aggregation is on the outer column (this is unusual). However, you don't need aggregation or order by. You only seem to care whether a row exists.

I think the logic is:

UPDATE datazone_report_resupply r
SET es_actual =
    (CASE WHEN EXISTS (SELECT 1
                       FROM suppliersnew s
                       WHERE St_contains(r.geom, s.geometry) AND
                             s.status IN ('Under construction', 'Unknown', 'Operational')
                      ) 
          THEN 1 ELSE 0
      END);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM