sql减去子查询和多个表

时间:2013-09-28 08:58:24

标签: sql sql-server sum subquery subtraction

如何从另一个表中减去子查询表的总和?

SELECT i.column1 * i.column2 AS Expr1
    , i.column1 * i.column2 - (SELECT SUM(table2.column1) AS Expr1 
                               FROM table2 
                               WHERE (table2.column3 = table1.column3)) AS derivedExpression
FROM table1

只有第一行中的derivedExpression是正确的。其余行为derivedExpression返回null。对于Expr1,一切都很好。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

SELECT i.column1 * i.column2 AS Expr1
    , i.column1 * i.column2 - (SELECT COALESCE(SUM(table2.column1), 0) AS Expr1 
                               FROM table2 
                               WHERE (table2.column3 = table1.column3)) AS derivedExpression
FROM table1