我有四张桌子,每张都看起来像
ID Value
1 23.43
2 34.23
1 32.23
3 11.25
每个表中的每个ID都可以有多个值条目。每个ID在所有四个表中都有值。
我想编写一个查询,为每个ID提供聚合结果。我想添加两个表的值,并从聚合中减去其他两个值。
如果要用伪代码写这个:
foreach ID
sumTable1 = sum(Table1.value) where ID=ID
sumTable2 = sum(Table2.value) where ID=ID
sumTable3 = sum(Table3.value) where ID=ID
sumTable4 = sum(Table4.value) where ID=ID
print ID . ": " . sumTable1+sumTable2-sumTable3-sumTable4
我可以在单个mySQL查询中执行此操作吗?
答案 0 :(得分:1)
这是未经测试的,但可能会按预期工作。
SELECT
t1.ID,
(SUM(t1.Value)+SUM(t2.Value)-SUM(t3.Value)-SUM(t4.Value)) AS aggregate_sum
FROM
t1 LEFT JOIN t2 ON t1.ID = t2.ID
LEFT JOIN t3 ON t1.ID = t3.ID
LEFT JOIN t4 ON t1.ID = t4.ID
GROUP BY t1.ID
编辑如果任何表格中没有ID,则将它们全部更改为LEFT JOIN
...
答案 1 :(得分:0)
这应该不对每个表中存在的值进行假设:
SELECT q.ID, SUM(q.Value) AS Total
FROM (SELECT ID, Value
FROM Table1
UNION ALL
SELECT ID, Value
FROM Table2
UNION ALL
SELECT ID, -Value AS Value
FROM Table3
UNION ALL
SELECT ID, -Value AS Value
FROM Table4) q
GROUP BY q.ID