select orderid, orderdate, shipvia, freight from orders t
結果如下:
select orderdate, shippers, coalesce(shippers1_freight, shippers2_freight, shippers3_freight) shippers_freight from (select orderdate, min(shipvia) shippers, max(decode(shipvia, 1, freight)) shippers1_freight, max(decode(shipvia, 2, freight)) shippers2_freight, max(decode(shipvia, 3, freight)) shippers3_freight from (select to_char(t.orderdate, 'yyyy/mm/dd') orderdate, shipvia, max(t.freight) freight from orders t group by to_char(t.orderdate, 'yyyy/mm/dd'), shipvia) group by orderdate order by orderdate)
接著就要把SQL分三層一一抽絲剝繭,想當然爾的從最內層開始解說:
- group by to_char(t.orderdate, 'yyyy/mm/dd'), shipvia -- 依據每日每個貨運公司取得最大運費 max(t.freight)。
- Mutil Row To One Row:利用group搭配max函數與decode將三個貨運公司分列為三個欄位。
- 利用coalesce函數依優先次數呈現貨運公司的運費。
nvl( string1, string2 ) =>判斷 string1 如果為 null 則呈現 string2。nvl 無法應付兩個以上null的判斷。
coalesce(string1, string2, string3) =>判斷 string1 為null則呈現 string2,若 string2 也是null則呈現 string3。
沒有留言:
張貼留言