没有使用Union All,有没有更好的方法来执行unpivoting?

问题描述 投票:1回答:1

请查看以下查询

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值之外,每个东西都是相同的。这花了太长时间。任何更好的方法来执行相同的操作。

样本输出

enter image description here

tsql sql-server-2012
1个回答
1
投票

您可以使用

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结果。

© www.soinside.com 2019 - 2024. All rights reserved.