我有2张桌子 T1(月份+年份是唯一的)
month year amount
10 2015 5000
11 2015 4000
T2
month year amount
10 2015 100
10 2015 200
10 2015 200
11 2015 200
我想按如下方式更新T1的金额字段 T1.amount = T1.amount - (匹配月份,年份的T2金额之和)
因此更新后T1应如下所示
month year amount
10 2015 4500
11 2015 3800
我不是SQL专家,请建议SQL实现上述功能,谢谢!
答案 0 :(得分:1)
您可以使用UPDATE
JOIN
对包含每月/每年Table2
总和的派生表执行操作:
UPDATE TABLE1 AS T1
JOIN ( SELECT month, year, SUM(amount) AS amount
FROM TABLE2
GROUP BY month, year) AS T2
ON T1.month = T2.month AND T1.year = T2.year
SET T1.amount = T1.amount - T2.amount;
修改强>
在sqlite中,您必须使用相关子查询来执行UPDATE
:
UPDATE TABLE1
SET amount = amount - (SELECT SUM(amount)
FROM TABLE2
WHERE TABLE1.month = TABLE2.month AND
TABLE1.year = TABLE2.year);
答案 1 :(得分:1)
Dispose
<强>解释强>
内部查询将总计每个(月,年)对的金额。
内部查询:
UPDATE T1
INNER JOIN
(
SELECT
`month`,
`year`,
SUM(amount) totalAmount
FROM T2
GROUP BY `month`,`year` ) t
ON t.`month` = T1.`month` AND t.`year` = T1.`year`
SET T1.amount = T1.amount - t.totalAmount;
对于您的样本数据,它返回如下结果:
我将其命名为SELECT
`month`,
`year`,
SUM(amount) totalAmount
FROM T2
GROUP BY `month`,`year`
table
t
现在,如果您将此month year totalAmount
10 2015 500
11 2015 200
表加入T1表t
和month
这意味着仅当year
T1.month equals t.month
AND 时才会加入来自两个表的行,然后您将更新相应数量的T1表格行,如下所示:
and T1.year equals t.year
因此,在此次更新后,您的T1.amount = T1.amount - t.totalAmount
应如下所示:
T1 table
结果:
SELECT
*
FROM T1
修改强>
在期望查询在SqlLite中工作时,您标记了问题month year amount
10 2015 4500
11 2015 3800
。
SQLlite doesn't support JOIN in Update statements。
Sqllite查询:
MySQL