请查看以下查询
select
ca.cnsmr_accnt_id,
cab.cnsmr_accnt_bal_amnt,
[Balance Short Name] = 'LOAN_AMOUNT' --LOAN_AMOUNT
from cnsmr_accnt ca
inner join cnsmr_accnt_bal cab on ca.cnsmr_accnt_id = cab.cnsmr_accnt_id
inner join bal_nm b on cab.bal_nm_id = b.bal_nm_id and b.bal_shrt_nm='OriBal' and b.bal_nm_actv_flg ='Y' UNION ALL
select
ca.cnsmr_accnt_id,
cab.cnsmr_accnt_bal_amnt,
[Balance Short Name] = 'BOM_POS' --BOM_POS
from cnsmr_accnt ca
inner join cnsmr_accnt_bal cab on ca.cnsmr_accnt_id = cab.cnsmr_accnt_id
inner join bal_nm b on cab.bal_nm_id = b.bal_nm_id and b.bal_shrt_nm='CurBal' and b.bal_nm_actv_flg ='Y' UNION ALL
select
ca.cnsmr_accnt_id,
cab.cnsmr_accnt_bal_amnt,
[Balance Short Name] = 'CURRENT_POS' --CURRENT_POS
from cnsmr_accnt ca
inner join cnsmr_accnt_bal cab on ca.cnsmr_accnt_id = cab.cnsmr_accnt_id
inner join bal_nm b on cab.bal_nm_id = b.bal_nm_id and b.bal_shrt_nm='CurBal' and b.bal_nm_actv_flg ='Y'
UNION ALL
select
ca.cnsmr_accnt_id,
cab.cnsmr_accnt_bal_amnt,
[Balance Short Name] = 'Total_Amount_Paid_till_date' --Total Amount Paid till date
from cnsmr_accnt ca
inner join cnsmr_accnt_bal cab on ca.cnsmr_accnt_id = cab.cnsmr_accnt_id
inner join bal_nm b on cab.bal_nm_id = b.bal_nm_id and b.bal_shrt_nm='TotPay' and b.bal_nm_actv_flg ='Y'
除了bal_shrt_nm值之外,每个东西都是相同的。这花了太长时间。任何更好的方法来执行相同的操作。
样本输出
您可以使用
SELECT ca.cnsmr_accnt_id,
cab.cnsmr_accnt_bal_amnt,
CA2.[Balance Short Name]
FROM cnsmr_accnt ca
INNER JOIN cnsmr_accnt_bal cab
ON ca.cnsmr_accnt_id = cab.cnsmr_accnt_id
INNER JOIN bal_nm b
ON cab.bal_nm_id = b.bal_nm_id
CROSS APPLY (SELECT 'LOAN_AMOUNT'
WHERE b.bal_shrt_nm = 'OriBal'
UNION ALL
SELECT 'BOM_POS'
WHERE b.bal_shrt_nm = 'CurBal'
UNION ALL
SELECT 'CURRENT_POS'
WHERE b.bal_shrt_nm = 'CurBal'
UNION ALL
SELECT 'Total_Amount_Paid_till_date'
WHERE b.bal_shrt_nm = 'TotPay') CA2([Balance Short Name])
WHERE b.bal_nm_actv_flg = 'Y'
AND b.bal_shrt_nm IN ( 'OriBal', 'CurBal', 'TotPay' );
它仍然有UNION ALL
但不重复连接四次然后UNION ALL
结果。