简体   繁体   中英

fetch rows dynamically from one table and get values from other table sum it up and insert into target table

x table has columns( Agency , datac )
Y table has columns( Agencyname , total )
EXAMPLE

Agency | datac
NET    | 100 
GOO    | 300 
NET    | 100 
GOO    | 100 

Agencyname | total
NET        |  
GOO        | 

first customer adds Agencyname then it gets update on table Y
From a dropdown menu in html i have made user to either choose NET OR GOO but what i want is how many values they may enter in table X .
i want their total sum to be inserted into table Y . so that my expected output looks like this

Agencyname | total
NET        | 200
GOO        | 400

The most straight forward way is probably an update with a subquery;

UPDATE TableY
SET total = (SELECT SUM(datac) FROM TableX WHERE Agency=AgencyName)

An SQLfiddle to test with .

UPDATE Y
SET Y.total = X.Total
FROM TABLE_Y Y INNER JOIN 
                  (
                    SELECT Agency, SUM(datac) AS Total
                    FROM TABLE_X 
                    GROUP BY Agency
                  ) X
ON Y.Agencyname = X.Agency

SQL FIDDLE TEST

SELECT agency, SUM(datac) FROM x GROUP BY agency

You want to combine this with INSERT INTO .

Although I do not see much sense in caching this easy-to-compute values...

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