看一條sqlsql
select q.*, r.goods_name from (select nvl(t.goods_code, s.goods_code) goods_code, t.buy_open_price, t.buy_position_price, t.buy_position_amount, s.sale_open_price, s.sale_position_price, s.sale_position_amount, (nvl(t.buy_position_amount, 0) - nvl(s.sale_position_amount, 0)) position_amount from (select opo.goods_code, opo.position_bs, sum(opo.open_price * opo.position_amount) / sum(opo.position_amount) buy_open_price, sum(opo.position_price * opo.position_amount) / sum(opo.position_amount) buy_position_price, sum(opo.position_amount) buy_position_amount from otc_trade_position_open opo where opo.position_bs = '1' and opo.account_type = '1' and position_bs = '2' group by opo.goods_code, opo.position_bs) t full outer join (select opo.goods_code, opo.position_bs, sum(opo.open_price * opo.position_amount) / sum(opo.position_amount) sale_open_price, sum(opo.position_price * opo.position_amount) / sum(opo.position_amount) sale_position_price, sum(opo.position_amount) sale_position_amount from otc_trade_position_open opo where opo.position_bs = '2' and opo.account_type = '1' and position_bs = '2' group by opo.goods_code, opo.position_bs) s on (t.goods_code = s.goods_code)) q left outer join otc_goods r on (q.goods_code = r.goods_code)
結果以下函數
再看下一個sqlspa
select q.*, r.goods_name from (select nvl(t.goods_code, s.goods_code) goods_code, t.buy_open_price, t.buy_position_price, t.buy_position_amount, s.sale_open_price, s.sale_position_price, s.sale_position_amount, (nvl(t.buy_position_amount, 0) - nvl(s.sale_position_amount, 0)) position_amount from (select opo.goods_code, opo.position_bs, sum(opo.open_price * opo.position_amount) / sum(opo.position_amount) buy_open_price, sum(opo.position_price * opo.position_amount) / sum(opo.position_amount) buy_position_price, sum(opo.position_amount) buy_position_amount from otc_trade_position_open opo where opo.position_bs = '1' and opo.account_type = '1' and position_bs = '1' group by opo.goods_code, opo.position_bs) t full outer join (select opo.goods_code, opo.position_bs, sum(opo.open_price * opo.position_amount) / sum(opo.position_amount) sale_open_price, sum(opo.position_price * opo.position_amount) / sum(opo.position_amount) sale_position_price, sum(opo.position_amount) sale_position_amount from otc_trade_position_open opo where opo.position_bs = '2' and opo.account_type = '1' and position_bs = '1' group by opo.goods_code, opo.position_bs) s on (t.goods_code = s.goods_code)) q left outer join otc_goods r on (q.goods_code = r.goods_code)
查詢方法同樣,就是條件變了一下,但是聯合查詢的商品名稱卻在上面一個裏面查詢不出來,而下面一個裏面顯示正常。分析緣由,nvl函數的問題,nvl(t.goods_code, s.goods_code) 前面一個查詢語句裏面,goods_code是取的s.goods_code,後面一個取的是t.goods_code.雖然值同樣,可是前面一個聯合查詢卻查詢不出來,有點詭異。code
解決方法:換成nvl2, 將上面代碼裏面的 nvl(t.goods_code,s.goods_code)換成nvl2(t.goods_code, t.goods_code, s.goods_code)上面存在的問題便可解決。blog