对一个表中的行求和并将其移动到另一个表

时间:2013-09-04 19:47:55

标签: sql sum

如何从一个表中对行进行求和(基于选定的标准)并将结果移到另一个表中。

我有一个与项目成本相关的表格:

表“费用”:

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

我希望将每个ID_CostCategory的“DoneValue”总和放入表“CostCategories”

表“CostCategories”:

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

非常感谢

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我不会存储这个,因为只要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;

现在,您可以参考该视图而不是引用该表,而PlannedDone总计将始终是最新的。