简体   繁体   English

从一个表动态获取行并从其他表获取值将其汇总并插入到目标表中

[英]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 ) x table有列( Agencydatac
Y table has columns( Agencyname , total ) Y表有列( Agencynametotal
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 第一个客户添加Agencyname然后它在表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 . 从html的下拉菜单中我已经让用户选择了NETGOO但我想要的是他们可以在表X输入多少个值。
i want their total sum to be inserted into table Y . 我希望他们的total sum能够插入表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 . 一个要测试的SQLfiddle

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 . 您想将其与INSERT INTO结合使用。

Although I do not see much sense in caching this easy-to-compute values... 虽然我没有看到缓存这个易于计算的值的意义......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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