我有3个包含如下数据的表格,我想将数据分组为单个输出。
table1
pid val
1 1
2 2
table2 id pid val 1 1 1 2 1 2 3 2 1
table3 id pid val 1 1 1 2 1 2 3 2 1 4 2 1
必需输出:
pid output 1 1 (table1 val + table2 Sum(val) - table3 Sum(val)) 2 1 (table1 val + table2 Sum(val) - table3 Sum(val))
请帮助进行最佳查询,无需任何临时表即可实现此目的。
答案 0 :(得分:0)
假设pid
是table1的主键,您可以使用此
SELECT
t1.pid,
t1.val + t2.sumval - t3.sumval
FROM
table1 t1
INNER JOIN
(SELECT
pid, SUM(val) as sumval
FROM
table2
GROUP BY
pid) t2
ON
t2.pid = t1.pid
INNER JOIN
(SELECT
pid, SUM(val) as sumval
FROM
table3
GROUP BY
pid) t3
ON
t3.pid = t1.pid;