在SQL Server中按多个表数据进行分组查询

时间:2016-09-23 03:16:00

标签: sql sql-server

我有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))

请帮助进行最佳查询,无需任何临时表即可实现此目的。

1 个答案:

答案 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;