SQL Sum重复计算

时间:2017-10-14 19:13:17

标签: sql

我的SQL重复计算'Fund1Amount'和'Fund2Amount'和'TotalAllDonations'我有一个记录,其中FundAmount1的值应该= 10而FundAmount2应该= 20但是它们等于20& 40,总数是两倍。我在同一张桌子上使用INNER JOIN两次abc_donationdetail,我不确定这是不是问题。

SELECT
    C.FirstName, C.LastName, 
    SUM(D.abc_totalamount) AS TotalAllDonations,
    SUM(CASE WHEN DBU.abc_fundidname = 'Fund1' THEN DBU.abc_amount END) AS Fund1Amount, 
    SUM(CASE WHEN DBE.abc_fundidname = 'Fund2' THEN DBE.abc_amount END) AS Fund2Amount
FROM
    Contact C 
INNER JOIN
    Account A ON C.parentcustomerid = A.accountid 
INNER JOIN
    Account PA ON A.parentaccountid = PA.accountid 
INNER JOIN
    abc_donation D ON D.abc_person = C.contactid 
LEFT JOIN
    abc_donationdetail DBU ON DBU.abc_donationid = D.abc_donationid 
                           AND DBU.abc_fundidname= 'Fund1' 
LEFT JOIN
    abc_donationdetail DBE ON DBE.abc_donationid = D.abc_donationid 
                           AND DBE.abc_fundidname = 'Fund2' 
LEFT JOIN
    abc_mmcs GD ON GD.abc_donor = C.contactid 
LEFT JOIN 
    sab_item LIBU ON LIBU.sab_itemid = GD.abc_companyid 
                  AND LIBU.sab_name = 'Fund1' 
LEFT JOIN
    sab_item LIBE ON LIBE.sab_itemid = GD.abc_companyid 
                  AND LIBE.sab_name = 'Fund2'

其中C.StateCode = 0 AND(GD.abc_enddate> GETDATE()或GD.abc_enddate为空)

由C.abc_memberid,C.FirstName,C.LastName,C.StateCode,A.name,A.parentaccountidname,A.dd_number,PA.dd_number,C.parentcustomeridname分组 按C.lastname

排序

当前

FN       LN   Total    Fund1    Fund2
James   Brown   70      40       30
Phillip Smith   160     60       100
Peter   Jones   80      40       40
Vincent Limp    48      48       NULL
Michael Collins 60      60       NULL

所需

FN       LN    Total    Fund1   Fund2
James   Brown   35       20      15
Phillip Smith   80       30      50
Peter   Jones   40       20      20
Vincent Limp    24       24     NULL
Michael Collins 30       30     NULL

任何帮助都会很棒。

由于

2 个答案:

答案 0 :(得分:0)

如果问题只是重复,那么只需创建一个子查询:

Select fld, sum(value)
from (select distinct fld, value from tbl) as a

答案 1 :(得分:0)

我在这里说不多,因为这里有很多桌子加入,我不知道他们的架构。最多,我建议您添加一个人的身份和资金ID,因为它会删除重复项。

> cutree(clusts, h = 0.155)
Error in cutree(clusts, h = 0.155) : 
  the 'height' component of 'tree' is not sorted (increasingly)

希望它有效!