使用SQL查询运行当前余额

时间:2017-08-30 19:10:08

标签: sql-server

我为我工作的小型非营利组织创建了一些存储过程。我们有一个表格,其中包含我们年度预算的信息,包括每个订单项的预算金额(即"宣传材料,500")。还有另一张表格,其中记录了我们的所有费用,以及它们来自哪个预算线。我想运行一个存储过程,从另一个表中减去该预算行中的所有费用和起始预算金额。我提出的用于测试程序的查询是这样的:

SELECT b.budget_line_ID, 
       b.budget_line_name, 
       b.[2017_amount] - e.amount AS CurrentBalance
FROM budget_detail AS b
INNER JOIN expenses AS e ON b.budget_line_ID = e.budget_line_id
WHERE e.budget_line_id = 4;

但是,当我运行查询时,会显示正确的列,但其中没有信息。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

或许像以下那样?

DECLARE @budget_line_id INT = 4;

SELECT 
    b.budget_line_id,
    b.budget_line_name,
    CurrentBalance = b.[2017_amount] - te.amount
FROM 
    dbo.budget_detail b
    CROSS APPLY (
        SELECT 
            amount = SUM(e.amount )
        FROM 
            dbo.expenses  e
        WHERE 
            b.budget_line_ID = e.budget_line_id
            AND e.budget_line_id = @budget_line_id
        ) te
WHERE 
    b.budget_line_id = @budget_line_id;

编辑:提供两种做同样事情的替代方法。

-- JOIN to a derived table...
SELECT 
    b.budget_line_id,
    b.budget_line_name,
    CurrentBalance = b.[2017_amount] - te.amount
FROM 
    dbo.budget_detail b
    JOIN (
        SELECT 
            e.budget_line_id,
            amount = SUM(e.amount )
        FROM 
            dbo.expenses  e
        WHERE
            e.budget_line_id = @budget_line_id
        GROUP BY 
            e.budget_line_id
        ) te
        ON b.budget_line_id = te.budget_line_id
WHERE 
    b.budget_line_id = @budget_line_id;

...

-- Correlated sub-query in the SELECT...
SELECT 
    b.budget_line_id,
    b.budget_line_name,
    CurrentBalance = b.[2017_amount] 
        - (SELECT 
            amount = SUM(e.amount )
        FROM 
            dbo.expenses  e
        WHERE 
            b.budget_line_ID = e.budget_line_id
            AND e.budget_line_id = @budget_line_id
        )
FROM 
    dbo.budget_detail b
WHERE 
    b.budget_line_id = @budget_line_id;