简体   繁体   English

对一个表中的行求和,然后将其移至另一表

[英]sum rows from one table and move it to another table

How can I sum rows from one table (based on selected critiria) and move the outcome to another table. 如何对一个表中的行求和(基于选定的critiria)并将结果移至另一表。

I have a table related to costs within project: 我有一个与项目内成本相关的表:

Table "costs": 表“费用”:

id| CostName |ID_CostCategory| PlanValue|DoneValue
-------------------------------------------------------
1 | books    |1              |100       |120
2 | flowers  |1              |90        |90
3 | car      |2              |150       |130
4 | gas      |2              |50        |45

and I want to put the sum of "DoneValue" of each ID_CostCategory into table "CostCategories" 我想将每个ID_CostCategory的“ DoneValue”之和放入表“ CostCategories”中

Table "CostCategories": 表格“ CostCategories”:

id|name |planned|done
------------------------
1 |other|190    |takes the sum from above table
2 |car  |200    |takes the sum from above table

Many thanks 非常感谢

INSERT INTO CostCategories(id,name,planned,done)
SELECT ID_CostCategory, CostName, SUM(PlanValue), SUM(DoneValue)
FROM costs GROUP BY ID_CostCategory, CostName

I would not store this, because as soon as anything changes in Costs then CostCategories will be out of date, instead I would create a view eg: 我不会存储它,因为一旦Costs发生任何变化,那么CostCategories将过时,相反,我将创建一个视图,例如:

CREATE VIEW CostCategoriesSum
AS
SELECT  CostCategories.ID,
        CostCategories.Name,
        SUM(COALESCE(Costs.PlanValue, 0)) AS Planned,
        SUM(COALESCE(Costs.DoneValue, 0)) AS Done
FROM    CostCategories
        LEFT JOIN Costs
            ON Costs.ID_CostCategory = CostCategories.ID
GROUP BY CostCategories.ID, CostCategories.Name;

Now instead of referring to the table, you can refer to the view and the Planned and Done totals will always be up to date. 现在,您可以引用该视图,而不必引用该表,并且“ PlannedDone总数将始终是最新的。

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

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