使用Coalesce的Sql Join和Sum

时间:2017-08-31 03:22:30

标签: sql qsqlquery

"Select COA.AccountNo, AccountName, (coalesce(DVDebit,0) + coalesce(JVDebit,0) + coalesce(CTDebit,0) ) AS Debit, (coalesce(CVCredit,0)+ coalesce(JVCredit,0))As Credit From ChartOfAccounts AS COA Left Join (Select AccountNo, Sum(Credit) AS CVCredit From CreditVouchersBody Group By AccountNo) AS CreditVoucher ON COA.AccountNo=CreditVoucher.AccountNo Left Join (Select AccountNo, Sum(Debit) AS DVDebit From DebitVouchersBody Group By AccountNo) AS DebitVoucher ON COA.AccountNo=DebitVoucher.AccountNo Left Join (Select AccountNo, Sum(Debit) As JVDebit, Sum(Credit) AS JVCredit From JournalVouchersBody Group By AccountNo) As JournalVoucher ON COA.AccountNo=JournalVoucher.AccountNo Left Join (Select AccountNoPayTo, Sum(Amount) As CTDebit From BankCheques Group By AccountNoPayTo) As BankdCheque ON COA.AccountNo=BankdCheque.AccountNoPayTo WHere COA.IsDetailed ='True' AND COA.AccountType ='Expense'"

此查询工作正常,并根据要求获取值。但是现在我在查询中没有改变任何内容,但我更改了数据库值,并且此查询仅返回0.数据库中的某些表中存在值。任何人都可以帮助我在这里我错了。

1 个答案:

答案 0 :(得分:0)

"仅返回0"意味着它为总和返回零,或者你的意思是它没有返回任何行?

如果你的意思是总和是零,那么很可能连接不再起作用了。您是否更改过ChartOfAccounts或其他表格中的AccountNo?

如果它没有返回任何行,则必须检查ChartOfAccounts,因为左连接不会减少您获得的行数。

如果ChartOfAccounts中有值,请检查IsDetailed和AccountType的值,并将它们与where条件进行比较。

select distinct IsDetailed from ChartOfAccounts

select distinct AccountType from ChartOfAccounts

对于其他人:这是他的可读形式的查询:

select
    COA.AccountNo
    ,AccountName
    ,(coalesce(DVDebit, 0) + coalesce(JVDebit, 0) + coalesce(CTDebit, 0))   as Debit
    ,(coalesce(CVCredit, 0) + coalesce(JVCredit, 0))                        as Credit
from ChartOfAccounts as COA
    left join
    (
        select
            AccountNo
            ,sum(Credit) as CVCredit
        from CreditVouchersBody
        group by AccountNo
    ) as CreditVoucher
        on COA.AccountNo = CreditVoucher.AccountNo
    left join
    (
        select
            AccountNo
            ,sum(Debit) as DVDebit
        from DebitVouchersBody
        group by AccountNo
    ) as DebitVoucher
        on COA.AccountNo = DebitVoucher.AccountNo
    left join
    (
        select
            AccountNo
            ,sum(Debit) as JVDebit
            ,sum(Credit) as JVCredit
        from JournalVouchersBody
        group by AccountNo
    ) as JournalVoucher
        on COA.AccountNo = JournalVoucher.AccountNo
    left join
    (
        select
            AccountNoPayTo
            ,sum(Amount) as CTDebit
        from BankCheques
        group by AccountNoPayTo
    ) as BankdCheque
        on COA.AccountNo = BankdCheque.AccountNoPayTo
where
    COA.IsDetailed      = 'True'
    and COA.AccountType = 'Expense';