我有两个SQL数据库表即
Cust_Table(CustID, CustName, custAddrs, CustMob, CustOpBal)
和
Trans_Table(TransId, CustID, TransAmt, TransType(bool dr/cr), Msg, TansDate)
现在我需要SQL Query来获取特定的(Bank Passbook)语句 客户ID?
Date Message Dt_Amount Cr_Amount Balance
我使用以下查询
SELECT t1.Trans_Date, t1.Trans_Msg,
(CASE WHEN t1.Trans_Type=1 THEN 'Cr' ELSE 'Dr' END) as Trans_Type,
t1.Trans_Amount,
SUM(t2.Trans_Amount*case when t2.trans_type = '1' then 1 else -1 end) as Balance
FROM [LNLCredit].[dbo].[Trans_Table] t1
INNER JOIN [LNLCredit].[dbo].[Trans_Table] t2
ON t1.cust_id = t2.cust_id AND t1.trans_id >= t2.Trans_ID
WHERE t1.Cust_ID=2
GROUP BY t1.cust_id,t1.trans_id,t1.trans_type,t1.Trans_Amount,t1.Trans_Date,t1.Trans_Msg;
工作正常。
但我也希望将Opening Balance(来自Cust_Table)添加到上述解决方案中。
请帮助??????
答案 0 :(得分:0)
试试这个..
SELECT t1.Trans_Date, t1.Trans_Msg,
(CASE WHEN t1.Trans_Type=1 THEN 'Cr' ELSE 'Dr' END) as Trans_Type,
t1.Trans_Amount,
SUM(t2.Trans_Amount*case when t2.trans_type = '1' then 1 else -1 end) as Balance,
c.CustOpBal
FROM [LNLCredit].[dbo].[Trans_Table] t1
INNER JOIN [LNLCredit].[dbo].[Trans_Table] t2
ON t1.cust_id = t2.cust_id AND t1.trans_id >= t2.Trans_ID
INNER JOIN Cust_Table C on C.cust_id = t1.cust_id
WHERE t1.Cust_ID=2
GROUP BY t1.cust_id,t1.trans_id,t1.trans_type,t1.Trans_Amount,
t1.Trans_Date,t1.Trans_Msg,C.CustOpBal;
您需要添加额外的INNER JOIN
并将openingBalance列添加到GROUP BY
和SELECT