項目中遇見統計每個課題組的”試劑“與”耗材“採購額與採購次數,當時查詢統計“試劑”的採購額與採購次數,然後查詢統計"耗材"的採購額與採購次數。這種方式效率很差,反反覆複訪問資料庫很多次,如果oracle提供了行列裝置函數就很好的解決此問題。
oracle 11g提供PIOVT
oracle 10g提供的有decode
decode的邏輯如下:
DECODE(value, if1, then1, if2,then2, if3,then3, . . . else )
如果value等於if1,那麼decode結果就是then1;如果value等於if2,那麼結果就是then2;如果value等於if3,那麼結果等於then3,如果value匹配不到任意值,就返回false。類是與C#的Switch:
Swtch(value){case "if1":"then1";break;case "if2":"then2";break;default :"other";break;}
由於我用的是oracle 10g,現在以decode為例:
1 select sum(sal), dt.dname2 from EMP t3 join dept dt4 on t.deptno = dt.deptno5 group by dname
顯示結果:
8750 ACCOUNTING
10875 RESEARCH
9400 SALES
裝置後:
select sum(decode(dt.dname, 'ACCOUNTING', sal)) ACCOUNTING, sum(decode(dt.dname, 'RESEARCH', sal)) RESEARCH, sum(decode(dt.dname, 'SALES', sal)) SALES from EMP t join dept dt on t.deptno = dt.deptno
顯示結果:
ACCOUNTING RESEARCH SALES
8750 10875 9400
修改關於試劑耗材的統計如下:
SELECT sum(DECODE(producttype, '試劑', od.sumprice)) sjprice, count(DECODE(producttype, '試劑', od.sumprice)) sjcount, sum(decode(producttype, '耗材', od.sumprice)) hcPrice, count(decode(producttype, '耗材', od.sumprice)) hcCount, nd.department FROM ORDER_INFO o join Order_Details od on o.orderid = od.orderid join user_info u on u.id = o.userid join neodepart nd on nd.id = u.department where 1 = 1 group by nd.department