2009年7月2日 星期四

Use Least function - Oracle 10g


/*
  Scenario:
  User 說,正常的情況下Column A 的值要>= Column B 且
             Column B 的值要>= Column C 且
             Column C 的值要>= Column D
  User 要找出不正常的資料。

  My solution: 使用Least Function
  Least((A-B),(B-C),(C-D)) < 0
*/

/* 建立測試Table&資料 */


create table test
(
  col_id varchar2(5),
  col_a integer,
  col_b integer,
  col_c integer,
  col_d integer
);

SQL> insert into test values ('00001',4,3,2,1);
已建立 1 個資料列.
SQL> insert into test values ('00002',9,1,2,5);
已建立 1 個資料列.
SQL> insert into test values ('00003',7,5,5,5);
已建立 1 個資料列.
SQL> insert into test values ('00004',3,4,9,5);
已建立 1 個資料列.
SQL> commit;

 
/* 找非正常的資料 */


select * from test
where least((col_a-col_b),(col_b - col_c),(col_c - col_d)) < 0;

COL_ID   COL_A   COL_B    COL_C   COL_D
---------- ---------- ---------- ---------- ----------
00002         9     1      2      5
00004         3     4      9      5