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

时间:2017-11-12 16:26:13

标签: tsql sql-server-2012

请查看以下查询

+-------------------------------------+
1.Push
2.Pop
3.Check whether the stack is full
4.Check whether the stack is empty
5.Check the Top Element
6.Display the Stack
7.Exit
+-------------------------------------+
Enter Choice:   1

Process returned 0 (0x0)   execution time : 6.304 s
Press any key to continue.

bal_shrt_nm 值外,其他所有内容都相同。这花了太长时间。任何更好的方法来执行相同的操作。

示例输出

enter image description here

1 个答案:

答案 0 :(得分: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结果。