从多个表中获取总和

时间:2012-09-07 17:23:23

标签: sql sql-server tsql sum

我在单个SQL语句中从多个表中提取Sums时遇到问题。

我有三个表tblCases,tblTimesheetEntries和tblInvoices tblCases与其他两个表中的每一个之间存在一对多的关系。

我目前正在使用以下SQL语句

SELECT c.CaseNo, SUM(i.InvFees), SUM(t.Fees)
FROM tblCases AS c
INNER JOIN tblInvoices AS i ON c.CaseNo = i.CaseNo
INNER JOIN tblTimesheetEntries AS t ON c.CaseNo = t.CaseNo
GROUP BY c.CaseNo
ORDER BY c.CaseNo;

但是,这似乎与发票金额重复。例如,如果案例中只有一张发票,但说4张时间表条目,则会计算4 x发票金额作为该表的总和。

如果我进行分组并改为运行以下SQL:

SELECT c.CaseNo, i.InvFees, t.Fees
FROM tblCases AS c
INNER JOIN tblInvoices AS i ON c.CaseNo = i.CaseNo
INNER JOIN tblTimesheetEntries AS t ON c.CaseNo = t.CaseNo    
ORDER BY c.CaseNo;

我可以看到这种情况正在发生,因为发票金额在所有4行中重复,例如

Case 1001,  Inv 001  950.00,  TimeFees  250.00
Case 1001,  Inv 001  950.00,  TimeFees  175.00
Case 1001,  Inv 001  950.00,  TimeFees  225.00
Case 1001,  Inv 001  950.00,  TimeFees  190.00

因此,发票总额是发票001金额的四倍。

我想从上述数据中返回的是一条求和线:

Case 1001,  Total Invoices 950.00,  Total TimeFees 840.00

如何在摘要中避免这种重复?

2 个答案:

答案 0 :(得分:5)

SELECT c.CaseNo,
       i.InvFees,
       t.Fees
FROM   tblCases AS c
       INNER JOIN (SELECT CaseNo,
                          Sum(InvFees) AS InvFees
                   FROM   tblInvoices
                   GROUP  BY CaseNo) AS i
         ON c.CaseNo = i.CaseNo
       INNER JOIN (SELECT CaseNo,
                          Sum(Fees) AS Fees
                   FROM   tblTimesheetEntries
                   GROUP  BY CaseNo) AS t
         ON c.CaseNo = t.CaseNo
ORDER  BY c.CaseNo; 

答案 1 :(得分:0)

尝试:

SELECT c.CaseNo, i.InvFees, sum(t.Fees)
FROM tblCases AS c
INNER JOIN tblInvoices AS i ON c.CaseNo = i.CaseNo
INNER JOIN tblTimesheetEntries AS t ON c.CaseNo = t.CaseNo    
group by c.CaseNo, i.InvFees