2

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

我有三个表 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

所以发票总数是 Invoice 001 金额的四倍。

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

Case 1001,  Total Invoices 950.00,  Total TimeFees 840.00

如何避免求和中的这种重复?

4

2 回答 2

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; 
于 2012-09-07T17:40:53.453 回答
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
于 2012-09-07T17:41:56.620 回答