简体   繁体   中英

Inner join update set postgresql

So I want to make the product between the sum of the number of days that a prisoner has worked and the multiplication coefficient for the specific task. I tried this code:

UPDATE prisoners
    SET nr_days_equaled = (SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
                           FROM prisoners pr 
                              INNER JOIN timesheets_prisoners tp ON pr.idprisoner= tp.idprisoner 
                              INNER JOIN nomenclature_activities_prisoners nap ON pp.idactivity=nap.idactivity)

But I get the following error:

column "nap.multiplication_coefficient" must appear in the GROUP BY clause or be used in an aggregate function

What can I do? Any ideas?

Welcome to StackOverflow.

When using any aggregate function (SUM, COUNT, MIN MAX etc.) together with any other field in your select statement, you must GROUP By the other fields selected. So in your case the compiler wants:

UPDATE prisoners
SET nr_days_equaled = 
(SELECT COALESCE (multiplication_coefficient*SUM(nr_days_worked),0)
FROM prisoners pr INNER JOIN timesheets_prisoners tp 
ON pr.idprisoner= tp.idprisoner 
INNER JOIN nomenclature_activities_prisoners nap 
ON pp.idactivity=nap.idactivity GROUP BY multiplication_coefficient)

However, without seeing the inner structure of your tables, I suspect that this is not really what you want. My suspicion is that you really need

SET nr_days_equaled = 
(SELECT COALESCE (SUM(multiplication_coefficient*nr_days_worked),0)
FROM prisoners pr INNER JOIN timesheets_prisoners tp 
ON pr.idprisoner= tp.idprisoner 
INNER JOIN nomenclature_activities_prisoners nap 
ON pp.idactivity=nap.idactivity)

The difference is that this version allows for different multiplication_coefficients for different work, but still sums the total. I stress that I am not sure. Please test by converting this to a SELECT statement before issuing the UPDATE.

EDIT

Having seen the structure, what you need is:

UPDATE prisoners
SET nr_days_equaled = SubQ.sumdaysmult
FROM
(SELECT pr.idprisoner, COALESCE (ppnap.sumdaysmult, 0) AS sumdaysmult FROM 
FROM prisoners pr LEFT JOIN (SELECT tp.idprisoner, SUM(tp.nr_days_worked
* nap.multiplication_coefficient) as sumdaysmult
FROM timesheets_prisoners tp 
INNER JOIN nomenclature_activities_prisoners nap 
ON tp.idactivity=nap.idactivity GROUP BY tp.idprisoner) tpnap
ON tpnap.idprisoner = pr.idprisoner) AS SubQ
WHERE SubQ.idprisoner = prisoners.idprisoner

您应该使用nap.multiplication_coefficient来使用group

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