简体   繁体   中英

UPDATE - SET with aggregate functions Access SQL

I have a tab with Agents and fields |ID_Agent | City | Payment|, i want to set their payments as a part of the sum of all agents in the concrete town.

UPDATED

To make shorter there is another call, but anyway, it doesn't work

UPDATE Agent as a1
    SET a1.Payment=  
    (SELECT AVG(a2.Payment) FROM Agent as a2 WHERE a2.City= a1.City)

I have read that it should work, but it doesn't so i don't know how to make this thing work
How it supposed to be:

Original table
|ID_Agent | City | Payment|  
|1        |London| 1600   |  
|2        |York  | 2000   |
|3        |London| 1000   |
|4        |York  | 1500   |
Result table
|ID_Agent | City | Payment|  
|1        |London| 1300   |  
|2        |York  | 1750   |
|3        |London| 1300   |
|4        |York  | 1750   |

EDIT:

 UPDATE Agent as a1 
 SET a1.Payment = a2._AvgPayment 
 FROM
     ( SELECT 
              City ,
              AVG(Payment) _AvgPayment
       FROM Agent 
       GROUP BY City 
     ) as a2
 WHERE a1.City = a2.City

But I think you can take inspiration from this

First prepare the data by grouping. And then do the update by joining the table. so we dont hold the table long time. The update goes faster, and SQL dont prepare the data for each row. Since it is already prepared in CTE.

;with AgentCTE as (

    SELECT city , sum(Payment) as TotalPayment, count(city) as AgentCount
        FROM agent
        GROUP BY city

)
UPDATE agnt set agnt.payment = (CTE.TotalPayment / CTE.AgentCount)
FROM Agent agnt 
    JOIN AgentCTE CTE on (agnt.city = CTE.city);

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