用另一个表的总和更新表中的列

时间:2019-01-10 00:58:01

标签: sqlite sql-update

我对SQL比较陌生,无法解决以下问题。

总之,我有两个表。我们可以调用第一个表people

name
--------
Margaret
Jim
Lola

第二个是与不同实体相关联的expenses种不同类型的列表:

name     | type     | amount
---------+----------+-------
Margaret | personal |    100
Jim      | business |     50
Lola     | business |    275
Margaret | business |     75
Lola     | personal |     10
Margaret | business |    150
Lola     | personal |     50
Jim      | business |    150

我想在第一个表中添加两列,使其看起来像这样:

name     | personal_expenses | business_expenses
---------+-------------------+------------------
Margaret |               100 |               275
Jim      |                 0 |               200
Lola     |               275 |                60

最初,我希望在添加personal_expensesbusiness_expenses列之后,可以通过以下查询完成此操作:

UPDATE people
SET personal_expenses = (
    SELECT SUM(amount)
    FROM expenses
    GROUP BY name
);

我也尝试过:

UPDATE people
SET personal_expenses = (
    SELECT SUM(amount)
    FROM expenses
    WHERE expenses.name = people.name
);

但同样无济于事。

我已经看过several answerssimilar questions,但是当我尝试-诚然,也许是错误地-将它们复制到sqlite3中时,我得到了(非常语法错误。

sqlite3中获得此分类总和的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您非常亲密!您在WHERE子句中忘记了另一个条件。同样,根据您在expense表中提供的示例数据,示例中的总和也不正确

ALTER TABLE `people` ADD COLUMN `personal_expense` INTEGER;
ALTER TABLE `people` ADD COLUMN `business_expense` INTEGER;

UPDATE people
SET personal_expense = (
      SELECT SUM(amount)
      FROM expenses
      WHERE expenses.type = 'personal'
        AND expenses.name = people.name ),

    business_expense = (
      SELECT SUM(amount)
      FROM expenses
      WHERE expenses.type = 'business'
        AND expenses.name = people.name )