SQL Server存储过程中的SUM()

时间:2017-07-31 03:56:31

标签: sql sql-server stored-procedures

我在这里尝试获取(EXPECTED)下面的数据。

ID | Project | SC   | PO   | INV
---+---------+------+------+-----
1  | test1   | NULL | 1    | NULL
2  | test2   | NULL | NULL | NULL

但根据我的存储过程,我得到的输出为

ID | Project | SC   | PO | INV
---+---------+------+----+-----
1  | test1   | NULL | 1  | NULL
2  | test2   | NULL | 1  | NULL

也许我的内部查询的结果是将Project test1收到的PO显示为PO test2。哪个不应该发生。因为项目'test1'出现在BudgetDetailsDetails表中。

任何帮助人员纠正我写过的sum()查询?

SELECT 
    BD.ID, BD.Project,
    (SELECT SUM(Amount) AS SC 
     FROM Details (NOLOCK) a 
     INNER JOIN BudgetDetails (NOLOCK) b ON a.Project = b.Project 
     WHERE ProcurementStatus = 'SC' AND a.Project = b.Project) AS SC,
    (SELECT SUM(Amount) as PO 
     FROM Details (NOLOCK) a 
     INNER JOIN BudgetDetails(NOLOCK) b ON a.Project = b.Project 
     WHERE ProcurementStatus = 'PO' AND a.Project = b.Project) AS PO,
    (SELECT SUM(Amount) as INV 
     FROM Details (NOLOCK) a 
     INNER JOIN BudgetDetails(NOLOCK) b ON a.Project = b.Project 
     WHERE ProcurementStatus = 'INV' AND a.Project = b.Project) AS INV
 FROM 
     BudgetDetails (NOLOCK) BD
 WHERE 
     BD.Quarter = @Quarter AND BD.Year = @Year
 GROUP BY 
     BD.ID, BD.Project

1 个答案:

答案 0 :(得分:0)

要修复您的查询,您的子查询中需要AND a.Project = BD.Project

最好使用CASE STATEMENT或PIVOT

重新编写它
 SELECT 
    BD.ID, BD.Project,
    SUM(CASE WHEN ProcurementStatus = 'SC' THEN Amount END) as SC,
    SUM(CASE WHEN ProcurementStatus = 'PO' THEN Amount END) as PO,
    SUM(CASE WHEN ProcurementStatus = 'INV' THEN Amount END) as INV,

 FROM   
        BudgetDetails (NOLOCK) BD
 LEFT JOIN 
        Details (NOLOCK) D  ON  BD.Project  = D.Project
 WHERE  
        BD.Quarter = @Quarter 
 AND    BD.Year = @Year
 GROUP BY 
        BD.ID, 
        BD.Project

编辑1:从INNER JOIN更改为LEFT JOIN以反映@ beginner的要求