0

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   |
Community
  • 1
  • 1
Vlad Samara
  • 47
  • 1
  • 1
  • 5

2 Answers2

0

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

i.signori
  • 585
  • 3
  • 16
  • Trying to set each rows Payment to the city avg for that column. Makes no sense. – jarlh Oct 24 '19 at 07:30
  • You're right, let's hope it is useful to at least see how to update through aggregate functions – i.signori Oct 24 '19 at 07:40
  • Not work for me "Syntax error (missing operator) in query expression Table_A.sum / Table_b.count FROM .... AS Table_A". Gonna try with INNER – Vlad Samara Oct 24 '19 at 07:47
0

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);
Andre
  • 26,751
  • 7
  • 36
  • 80
Nats N
  • 41
  • 1