日期:2014-05-16  浏览次数:20480 次

order by原来也可以这样

You Asked?(Jump to Tom's latest followup)

Hi Tom,

I have scenario like , For example I have table with  a Column of values 
1,2,3,4,5  but i need the output like  2,3,4,5,1, for this i found one solution 
but i hope this is not the generic one, could  you please help me.., Below i 
have explained scenario with the example

CREATE TABLE TEST1 (c1 NUMBER(2));

INSERT INTO TEST1 ( C1 ) VALUES ( 
2); 
INSERT INTO TEST1 ( C1 ) VALUES ( 
3); 
INSERT INTO TEST1 ( C1 ) VALUES ( 
1); 
INSERT INTO TEST1 ( C1 ) VALUES ( 
5); 
INSERT INTO TEST1 ( C1 ) VALUES ( 
4); 
COMMIT;

SELECT a.c1
  FROM TEST1 a, (SELECT MAX (c1) c1
                   FROM TEST1) v, (SELECT MIN (c1) c1
                                     FROM TEST1) u ORDER BY DECODE (a.c1, u.c1, 
v.c1+a.c1, a.c1)

Output

C1
------
2
3
4
5
1


2.I have a Before Insert Trigger, After insert trigger and a Check Constraint on 
a same table, so when i insert a row into the table which one fires first, Could 
you please justify


waiting for your valuable answers
 
and we said...
seems like a very very strange sort of "thing".  But always - very very VAGUE.  
I presume you want the "least element last"


since nulls sort "last"

ops$tkyte@ORA10GR2> select * from test1
  2  order by decode( c1, (select min(c1) from test1), to_number(null), c1);

        C1
----------
         2
         3
         4
         5
         1

the to_number is 100% relevant, we want the decode to return a number, not a 
string.


About all you want to say with regards to the last question is that the BEFORE 
TRIGGER will fire and then the after/check constraint will be done.

If you have some reliance on the order of the check/after trigger - we need to 
talk, you have a seriously flawed design issue we'll need to resolve.


If the after trigger fires first and the check constraint fails, the after 
trigger will rollback.

If the after trigger fires second and the check constraint fails, the after 
trigger will not have happened so it'll be just as if the after trigger had 
fired since no work will persist.



So, while we could set up a test case to see which order they appear to fire in 
- that would be entirely an empirical observation subject to change.  There 
should be no logical impact on your application if they go A and then B or B and 
then A however.  If there is, we need to fix that :)