T-SQL SUM由三个表组成

时间:2018-04-24 10:02:05

标签: sql sql-server-2008 tsql

我已经创建了一个SqlFiddle http://www.sqlfiddle.com/#!18/b9363f/4来解释我的问题

我有三个实体“发票” - > 1:n->“付款” - > 1:n->“拍摄”

每个实体都拥有它自己的总数(金额),我必须写一个SELECT,它将(每个实体的)数量相加以匹配父项的数量......问题在于回复的“付款”每次拍摄。

SELECT I.invoice_number AS invoiceNumber, I.amount AS invoiceAmount, SUM(P.amount) AS paymentAmount, SUM(T.amount) as takingAmount 
FROM Invoice AS I
INNER JOIN Payment AS P ON P.invoice_number = I.invoice_number
INNER JOIN Taking AS T ON T.invoice_number = P.invoice_number AND T.payment_row = P.payment_row
GROUP BY I.invoice_number, I.amount, P.invoice_number

结果是(第一行错误)

invoiceNumber   invoiceAmount   paymentAmount   takingAmount
1               100.2           300.4           100.2
2               98.4            98.4            98.4

我如何将此一组分组,避免付款的“金额”“回复”

[EDITED] 结果预期

invoiceNumber   invoiceAmount   paymentAmount   takingAmount
1               100.2           100.2           100.2
2               98.4            98.4            98.4

2 个答案:

答案 0 :(得分:1)

您必须使用两个子查询编写查询以计算付款和获取金额。

您的查询将是:

 SELECT I.invoice_number, SUM(I.amount),
     (SELECT SUM(P.amount)
     FROM Payment P
     WHERE P.invoice_number = I.Invoice_number) as Payment_Amount,
     (SELECT SUM(T.amount)
     FROM Taking T
     WHERE T.invoice_number = I.Invoice_number) as Taking_Amount
 FROM Invoice I
 group by I.invoice_number

这里是Sql Fiddle

答案 1 :(得分:0)

使用apply运算符:

SELECT I.invoice_number AS invoiceNumber, I.amount AS invoiceAmount, 
       p.paymentAmount, t.takingAmount 
FROM Invoice AS I cross apply (
    select SUM(amount) as paymentAmount
    from Payment 
    where invoice_number =  i.invoice_number
) p cross apply (
   select SUM(amount) as takingAmount
   from Taking as takingAmount
   where invoice_number =  i.invoice_number
) t;

您的joins有一些冗余过滤,因此会产生一致性总和