with tmp1 as( SELECT DISTINCT(Qty_Asset) CurrencyCode FROM board), tmp2 as( select 'Previous Day Ending Balance' transType, 1 sort union all select 'Client Buy',2 union all select 'Client Sell', 3 union all select 'Transfer (Deposit)', 4 union all select 'Transfers (Withdraw)', 5 ), tmp3 as( SELECT Asset_Name, SUM(ifnull(Asset_Amount,0)) Asset_Amount_T, SUM(ifnull(Market_Value, 0)) Market_Value_T, SUM(ifnull(Buy_Amount_T,0)) Buy_Amount_T, SUM(ifnull(Buy_Market_Value,0)) Buy_Market_Value_T, SUM(ifnull(Sell_Amount_T,0)) Sell_Amount_T, SUM(ifnull(Sell_Market_Value,0)) Sell_Market_Value_T, SUM(ifnull(Deposit_Qty_T,0)) Deposit_Qty_T, SUM(ifnull(Withdrawal_Qty_T,0)) Withdrawal_Qty_T, SUM(ifnull(Safekeep_Other_Balance,0)) Safekeep_Other_Balance FROM asset_hist INNER JOIN tmp1 ON Asset_Name = tmp1.CurrencyCode WHERE Broker_ID = 'VC' AND Trade_D = '20180530' GROUP BY Asset_Name) select * from tmp3;