简体   繁体   中英

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.

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"

Table "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:

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.

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