如何在sql server中对两行的值求和

时间:2017-10-09 04:12:23

标签: sql-server

SELECT (
    (SUM(t_price) - SUM(a_dvpay)) - (
        SELECT SUM(inst_amount)
        FROM installment
        WHERE uid = user_info.uid
    )        
) AS remaining
FROM user_info
WHERE faculty_id = @faculty_id
GROUP BY uid;

此SQL查询在多行中返回剩余结果。我想将剩余的值加总为剩余总数SQL Query Result

3 个答案:

答案 0 :(得分:1)

删除Group By子句。

SELECT ((sum(t_price) - sum(a_dvpay))-(select sum(inst_amount) from installment where uid=user_info.uid)) as remaining  FROM user_info WHERE (faculty_id = @faculty_id)**strong text**

答案 1 :(得分:0)

我找到了一个可以返回所需内容的解决方案:

SELECT SUM(remaining) FROM (
    SELECT sum(t_price - a_dvpay) as remaining  
    FROM user_info
    WHERE faculty_id = 1
    UNION
    SELECT -SUM(COALESCE(inst_amount,0))
    FROM installment inst
    WHERE uid IN (SELECT DISTINCT user_info.uid FROM user_info WHERE faculty_id = 1)
) x

测试它:http://sqlfiddle.com/#!9/e6d341/11

答案 2 :(得分:0)

因此它将是installment表中的金额总和,并且我假设并非所有{(1}}}成员都有记录。为了满足这一要求,我使用faculty_id来处理COALESCE表中的NULLS

installment