合并不在更新连接中工作

时间:2014-09-11 01:01:40

标签: sql sql-server join sql-update coalesce

我有一个更新查询,我试图在三个不同的交易表存款,支票和一般条目上找到多个账户的净利息。我遇到的问题是,当其中一个表没有利息帐户的贷款编号条目时,select不返回任何内容,随后在生产表中也显示空值。如果从利息帐户返回行,则否定其他表。如果所有三个表都有一行感兴趣,那么查询工作正常。

以下是代码:

UPDATE Prod
  SET Prod.InterestSpread = (T1.Amount+T2.Amount-T3.Amount)
FROM dbo.Production_Pipeline as Prod
LEFT JOIN
(
  SELECT LoanNumber,COALESCE(SUM(JournalLineAmount),0)as Amount
  FROM dbo.GeneralLedger
  WHERE (JournalLineAccountRefListID = 'BB0000-1103842703' 
  OR JournalLineAccountRefListID = '800001DA-1202763722')
) AS T1
ON T1.LoanNumber = Prod.LoanNumber
LEFT JOIN
(
  SELECT LoanNumber,COALESCE(SUM(DepositLineAmount),0)as Amount
  FROM dbo.DepositLedger
  WHERE ( DepositLineAccountRefListID = 'BB0000-1103842703' 
  OR DepositLineAccountRefListID = '800001DA-1202763722')
) AS T2
ON T2.LoanNumber = Prod.LoanNumber
LEFT JOIN
(
  SELECT LoanNumber,COALESCE(SUM(ExpenseLineAmount),0) AS Amount
  FROM dbo.CheckLedger
  WHERE(ExpenseLineAccountRefListID = '800002B4-1308771936'
    OR ExpenseLineAccountRefListID = 'D30000-1105022008'
    OR ExpenseLineAccountRefListID = '8000029E-1283179936'
    OR ExpenseLineAccountRefListID = 'BB0000-1103842703'
    OR ExpenseLineAccountRefListID = '800001DA-1202763722')
) AS T3
ON T3.LoanNumber = Prod.LoanNumber

因此,inccorect结果更新看起来像是 T1Amount:496.08
T2Amount:
T3Amount:373.92
兴趣点差:NULL

我已经对这个网站做了一些相当多的研究,但是,我无法将你的智慧应用于我的具体问题,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

COALESCE语句移至JOIN之外,并将其从子查询中删除:

UPDATE Prod
SET Prod.InterestSpread =
      COALESCE(T1.Amount,0)+COALESCE(T2.Amount,0)-COALESCE(T3.Amount,0)
...

问题是你的子查询没有返回任何结果,因此内部的coalesce无法应用于该字段。通过在外部联接之外使用它,可以确保结果为null,它可以正确转换。