0

如何汇总一个表中的行(基于选定的标准)并将结果移动到另一个表。

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

表“成本”:

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”中

表“成本类别”:

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

非常感谢

4

2 回答 2

0
INSERT INTO CostCategories(id,name,planned,done)
SELECT ID_CostCategory, CostName, SUM(PlanValue), SUM(DoneValue)
FROM costs GROUP BY ID_CostCategory, CostName
于 2013-09-04T20:01:39.463 回答
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;

现在,您可以参考视图,而不是参考表,Planned并且Done总数将始终是最新的。

于 2013-09-04T20:08:25.137 回答