sql中的错误1241

时间:2012-03-18 08:56:46

标签: sql

我正在尝试使用sql查询从不同的表中减去两个值来确定每个客户端的剩余余额。这是我的SQL查询。但我得到一个错误1241(操作数应包含1列)。我已经写了别名“BALANCE”。

SELECT tblClientInfo.ClientID, 
  (SELECT tblLoanPayment.ClientID,  
     SUM(tblLoanPayment.AmountPaid) FROM tblLoanPayment) -
  (SELECT tblLedger.ClientID,  tblLedger.LoanAmount from tblLedger) AS BALANCE
FROM tblClientInfo, tblLedger, tblLoanPayment 
WHERE tblClientInfo.ClientID = 1
你能帮帮我吗?在此先感谢。

2 个答案:

答案 0 :(得分:3)

您正在选择两列!

(Select tblLoanPayment.ClientID,  sum(tblLoanPayment.AmountPaid)

您必须选择仅一列才能使用数学运算符!

SELECT  
  (SELECT SUM(t.AmountPaid)
   FROM tblLoanPayment t
   WHERE t.ClientID = 1) -
  (SELECT t.LoanAmount 
   from tblLedger
   WHERE t.ClientID = 1)
FROM dual; 

答案 1 :(得分:0)

您的第二个子选择是提供两列,-仅对单个值进行操作。

如果没有付款,您的子选择也可能会产生奇怪的结果;如果您只是将其重写为JOIN,我会发现查询更容易阅读。

SELECT ci.ClientID, ledger.LoanAmount - COALESCE(SUM(AmountPaid), 0) Remaining
FROM tblClientInfo ci 
JOIN tblLedger ledger ON ci.ClientID=ledger.ClientId 
LEFT JOIN tblLoanPayment lp ON ci.ClientID=lp.ClientId
GROUP BY ci.ClientID, ledger.loanAmount

演示here