Sorting character column ( used in order by clause dynamically)
Hi,
I need help on sorting character-based numbers. Like say, I want to sort customers based on street numbers(which is a character string being used in the
order by clause) they live in.
The criteria are :
i. Numbers must take precedence.
This being a character string, 1000001 comes before 2. This shouldn't happen. And you cannot use to_number
since using it with a string having characters in it would raise an error.
ii. If only a single alphabet occurs as the last character, then treat the whole string as a number except the last character and then sort it
as if sorting a number. Something like : if you have 1000A, 200D, 200B, 1000X, the result would be 200B,200D,1000A,1000X.
iii. if a character occurs elsewhere in the string, then perform the search normally as if performing a character search.
The output of the following data :
100
A101
B100A
110C
C120B
120
100020
120C
C1100
100D
would be like :
100
100D
110C
120
120C
100020
A101
B100A
C120B
C1100
Please note that the sort is being done dynamically, so I could have access to the values of the street numbers only during run time.
Any help is really appreciated.
Thanks in advance.
Regards,
Anil.
Create a function to test whether the column is numeric :
create FUNCTION is_numeric(v_number VARCHAR2)
RETURN INTEGER
IS
l_number NUMBER;
BEGIN
IF INSTR(UPPER(v_number),'E') > 0 THEN
RETURN 0;
END IF;
l_number := TO_NUMBER(v_number);
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
And try this query
Assume the table name is TEST with column STREET
select * from TEST
order by case is_numeric(STREET) when 1 then LPAD(STREET,20, ' ') else STREET end
Please make sure that 20 mentioned above is the column size for STREET.
Hope this helps.
-Nags
Similar Messages
-
Order by clause Dynamic in Oracle function
How can i get order by Clause Dynamic in Oracle function
My function Returns sql query with SYS_REFCURSOR . and i will pass the order by column as input parameter
create or replace
FUNCTION TEST_SSK
p_srot number
RETURN SYS_REFCURSOR
AS
C_testssk SYS_REFCURSOR;
BEGIN
OPEN C_TESTSSK FOR
SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER
order by P_SROT;
return C_testssk;
end;Edited by: user10736825 on Dec 22, 2010 11:34 AMyou can go for a dynamic query ;)
create or replace
FUNCTION TEST_SSK
p_srot number
RETURN SYS_REFCURSOR
AS
C_testssk SYS_REFCURSOR;
l_str VARCHAR2(4000);
l_order VARCHAR2(100);
BEGIN
l_str := 'SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER ';
IF p_sort = 'LC'
THEN
l_order := ' ORDER BY LOAN_CODE ';
ELSIF p_sort = 'LD'
THEN
l_order := ' ORDER BY LOAN_DATE ';
END IF;
l_str := l_str || l_order ;
OPEN C_TESTSSK FOR l_str;
return C_testssk;
end; -
Can i assign an 'order by' clause dynamically in forms ??
I know it's possible to assign an 'order by' clause in reports with lexical parameter.
for example..
select A
from TABLE
where A is not null
&V_ORDERBY
In this, v_orderby might be 'order by name' like that,,,
can i assign an 'order by' clause dynamically IN FORMS ??
If you understan my question, please answer to me,,,ㅜㅜHave you tried this build-in function?
SET_BLOCK_PROPERTY('[BLOCK_NAME]', ORDER_BY, 'SORTCOL1, SORTCOL2...');
Where 'SORTCOL1, SORTCOL2...' are the table columns name. -
How to use "Order by" clause dynamically on LOV values in 10g r2 forms
Hi ,
I have following requirement,please guide me.
1 Create a List Of Values with 2 fields, Code and Description
2. Do not use order by clause in record Group Query
3. Attach this LOV to a field in Form
4. When user invokes the LOV user will see two fields in LOV with header as Code and Description
5. Now when user clicks on Column Header “Code” then LOV should be sorted on Code
6. And if User clicks on Column Header “Description” then LOV should be sorted on Description
Thanks in Advance.Kindly post this problem in this forum ->
[Forms Forum|http://forums.oracle.com/forums/forum.jspa?forumID=82]
And, close this thread by marked it as answered. ;)
Regards.
Satyaki De. -
Slow SQL output when table alias is NOT used in order by clause
Hi guys,
My query is based on Oracle 9208
I have a table TAB1 with 68000 records with transaction_id as the primary key in this table (unique index).
I have another TAB2 with the same number of records again with transaction_id in this table (foreign key to above).
I have the below query that gets executed via an application:-
SELECT TO_CHAR(V1.TRANSACTION_ID), V1.POLICY_ID, V1.REQUEST_TYPE
FROM <VIEW> V1 WHERE V1.CERT_SERIAL_NUM=56192 AND
(V1.AUTH_GROUP_ID=0 OR V1.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
BY TRANSACTION_ID ASC
The above view V1 is created as below:-
CREATE OR REPLACE FORCE VIEW "V1"
("TRANSACTION_ID",
"PARENT_TRANSACTION_ID",
"CA_DN_ID",
"AUTH_GROUP_ID",
"POLICY_ID",
"REQUEST_TYPE",
"REQUEST_STATUS",
"EE_DN_HASH",
"EE_DN",
"EE_EMAIL_HASH",
"EE_EMAIL",
"KEY_USAGE",
"SMART_CARD_SERIAL",
"CERT_TYPE",
"CERT_SERIAL_NUM",
"CERT_INDEX",
"RENEWAL_FLAG",
"ARCHIVE_FLAG",
"TIME_RECEIVED",
"DOWNLOADED",
"REQUEST_DATA",
"ACTION",
"STEP_NUM")
AS
SELECT
T1.transaction_id,
T1.parent_transaction_id,
T1.ca_dn_id,
V2.auth_group_id,
V2.policy_id,
T1.request_type,
T1.request_status,
T2.ee_dn_hash,
T2.ee_dn,
T2.ee_email_hash,
T2.ee_email,
T2.key_usage,
T2.smart_card_serial,
T2.cert_type,
T2.cert_serial_num,
T2.cert_index,
T2.renewal_flag,
T2.archive_flag,
T1.time_received,
T1.downloaded,
T1.request_data,
V2.action,
V2.step_num
FROM TAB1
<ANOTHER VIEW> V2,
TAB2 T1,
TAB2 T2
WHERE
T1.transaction_id = T2.transaction_id
AND
V2.policy_id = T1.policy_id
order by transaction_id;
The query at the top runs within milliseconds if the VIEW is created as :-
order by t2.transaction_id
But without the alias "t2" in the order by, the query takes about 1 1/2 minutes
Can you tell me why? I thought if you ordering by primary key (lesser number of values compared to foreign key values), the query should be faster..no?
Thanks in advanceThanks for keeping up with this issue Hemant.
Here are the plans for each case.
I would be very interested in how you'd recognize which plan is the best and what are the derivatives.
I don't much (or rather anything!) what is 'card' values, 'cost' values etc which I believe are used to decide the best plan of the lot.
Thanks again
Note TAB1 and TAB2 are from view definition posted initially
1) Execution Plan for VIEW1 <<-- With ORDER BY" clause but no table ailas (order by transaction_id)
SQL> EXPLAIN PLAN FOR SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=24293 AND
3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
4 BY TRANSACTION_ID ASC
5 /
Explained.
Elapsed: 00:00:01.00
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 3 | 195 | 17 |
|* 1 | COUNT STOPKEY | | | | |
| 2 | VIEW | VIEW1 | 17 | 1105 | 17 |
|* 3 | SORT ORDER BY STOPKEY | | 17 | 38573 | 17 |
| 4 | NESTED LOOPS | | 17 | 38573 | 10 |
| 5 | MERGE JOIN CARTESIAN | | 1 | 167 | 9 |
| 6 | VIEW | VIEW2 | 1 | 52 | 8 |
| 7 | SORT UNIQUE | | 1 | 156 | 8 |
| 8 | NESTED LOOPS | | 1 | 156 | 6 |
| 9 | NESTED LOOPS | | 1 | 143 | 6 |
| 10 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
|* 11 | HASH JOIN | | 1 | 104 | 5 |
| 12 | NESTED LOOPS | | 1 | 52 | 2 |
|* 13 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
|* 14 | INDEX UNIQUE SCAN | (PK_TAB4) | 1 | 13 | |
| 15 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
| 16 | VIEW PUSHED PREDICATE | View3 | 1 | 13 | |
| 17 | NESTED LOOPS | | 1 | 52 | 2 |
| 18 | NESTED LOOPS | | 1 | 39 | 2 |
|* 19 | INDEX UNIQUE SCAN | (PK_TAB6) | 1 | 13 | 1 |
|* 20 | INDEX RANGE SCAN | (PK_TAB7) | 1 | 26 | 1 |
|* 21 | INDEX UNIQUE SCAN | (PK_TAB8) | 1 | 13 | |
| 22 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
|* 23 | INDEX UNIQUE SCAN | (PK_TAB9) | 1 | | |
|* 24 | INDEX UNIQUE SCAN | (PK_TAB10)| 1 | 13 | |
| 25 | BUFFER SORT | | 1 | 115 | 9 |
| 26 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 115 | 1 |
|* 27 | INDEX RANGE SCAN | (TAB2_IDX2)| 1 | | |
|* 28 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 25224 | 1 |
|* 29 | INDEX UNIQUE SCAN | (PK_TAB1) | 1 | | |
Predicate Information (identified by operation id):
1 - filter(ROWNUM<=3)
3 - filter(ROWNUM<=3)
11 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
13 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
14 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
19 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
20 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
21 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
23 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
24 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
27 - access("TAB2"."CERT_SERIAL_NUM"=24293)
28 - filter("View2"."POLICY_ID"="TAB1"."POLICY_ID")
29 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
Note: cpu costing is off
54 rows selected.
Elapsed: 00:00:01.81
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
Statistics
39 recursive calls
0 db block gets
629 consistent gets
0 physical reads
104 redo size
5169 bytes sent via SQL*Net to client
405 bytes received via SQL*Net from client
5 SQL*Net roundtrips to/from client
31 sorts (memory)
0 sorts (disk)
54 rows processed
2) Execution Plan for VIEW1 <<-- With ORDER BY" clause and table alias (order by TAB2.transaction_id)
SQL> explain plan for SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=30003 AND
3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
4 BY TRANSACTION_ID ASC
5 /
Explained.
Elapsed: 00:00:10.20
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 3 | 195 | 14 |
| 1 | SORT ORDER BY | | 3 | 195 | 14 |
|* 2 | COUNT STOPKEY | | | | |
| 3 | VIEW | VIEW1 | 17 | 1105 | 13 |
| 4 | NESTED LOOPS | | 17 | 38573 | 13 |
| 5 | MERGE JOIN CARTESIAN | | 1 | 167 | 12 |
|* 6 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 115 | 4 |
| 7 | INDEX FULL SCAN | (TAB2_IDX) | 94 | | 1 |
| 8 | BUFFER SORT | | 1 | 52 | 8 |
| 9 | VIEW | VIEW2 | 1 | 52 | 8 |
| 10 | SORT UNIQUE | | 1 | 156 | 8 |
| 11 | NESTED LOOPS | | 1 | 156 | 6 |
| 12 | NESTED LOOPS | | 1 | 143 | 6 |
| 13 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
|* 14 | HASH JOIN | | 1 | 104 | 5 |
| 15 | NESTED LOOPS | | 1 | 52 | 2 |
|* 16 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
|* 17 | INDEX UNIQUE SCAN | (PK_TAB4) | 1 | 13 | |
| 18 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
| 19 | VIEW PUSHED PREDICATE | View3 | 1 | 13 | |
| 20 | NESTED LOOPS | | 1 | 52 | 2 |
| 21 | NESTED LOOPS | | 1 | 39 | 2 |
|* 22 | INDEX UNIQUE SCAN | (PK_TAB6) | 1 | 13 | 1 |
|* 23 | INDEX RANGE SCAN | (PK_TAB7) | 1 | 26 | 1 |
|* 24 | INDEX UNIQUE SCAN | (PK_TAB8) | 1 | 13 | |
| 25 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
|* 26 | INDEX UNIQUE SCAN | (PK_TAB9) | 1 | | |
|* 27 | INDEX UNIQUE SCAN | (PK_TAB10) | 1 | 13 | |
|* 28 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 25224 | 1 |
|* 29 | INDEX UNIQUE SCAN | (PK_TAB1) | 1 | | |
Predicate Information (identified by operation id):
2 - filter(ROWNUM<=3)
6 - filter("TAB2"."CERT_SERIAL_NUM"=30003)
14 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
16 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
17 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
22 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
23 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
24 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
26 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
27 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
28 - filter("VIEW2"."POLICY_ID"="TAB1"."POLICY_ID")
29 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
Note: cpu costing is off
53 rows selected.
Elapsed: 00:00:08.29
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
Statistics
1079 recursive calls
0 db block gets
597 consistent gets
21 physical reads
0 redo size
5177 bytes sent via SQL*Net to client
405 bytes received via SQL*Net from client
5 SQL*Net roundtrips to/from client
63 sorts (memory)
0 sorts (disk)
53 rows processed
3) Execution Plan for VIEW1 <<-- Without any "ORDER BY" clause
SQL> explain plan for SELECT TO_CHAR(QT.TRANSACTION_ID), QT.POLICY_ID, QT.REQUEST_TYPE
2 FROM <VIEW1> QT WHERE QT.CERT_SERIAL_NUM=30003 AND
3 (QT.AUTH_GROUP_ID=0 OR QT.AUTH_GROUP_ID=1) AND ROWNUM <= 3 ORDER
4 BY TRANSACTION_ID ASC
5 /
Explained.
Elapsed: 00:00:10.20
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost |
| 0 | SELECT STATEMENT | | 3 | 213 | 11 |
| 1 | SORT ORDER BY | | 3 | 213 | 11 |
|* 2 | COUNT STOPKEY | | | | |
| 3 | NESTED LOOPS | | 17 | 1207 | 10 |
| 4 | MERGE JOIN CARTESIAN | | 1 | 32 | 9 |
| 5 | VIEW | VIEW2 | 1 | 26 | 8 |
| 6 | SORT UNIQUE | | 1 | 156 | 8 |
| 7 | NESTED LOOPS | | 1 | 156 | 6 |
| 8 | NESTED LOOPS | | 1 | 143 | 6 |
| 9 | NESTED LOOPS OUTER | | 1 | 117 | 5 |
|* 10 | HASH JOIN | | 1 | 104 | 5 |
| 11 | NESTED LOOPS | | 1 | 52 | 2 |
|* 12 | TABLE ACCESS FULL | TAB3 | 1 | 39 | 2 |
|* 13 | INDEX UNIQUE SCAN | PK_TAB4 | 1 | 13 | |
| 14 | TABLE ACCESS FULL | TAB5 | 82 | 4264 | 2 |
| 15 | VIEW PUSHED PREDICATE | VIEW3 | 1 | 13 | |
| 16 | NESTED LOOPS | | 1 | 52 | 2 |
| 17 | NESTED LOOPS | | 1 | 39 | 2 |
|* 18 | INDEX UNIQUE SCAN | PK_TAB6 | 1 | 13 | 1 |
|* 19 | INDEX RANGE SCAN | PK_TAB7 | 1 | 26 | 1 |
|* 20 | INDEX UNIQUE SCAN | PK_TAB8 | 1 | 13 | |
| 21 | TABLE ACCESS BY INDEX ROWID| TAB9 | 3 | 78 | 1 |
|* 22 | INDEX UNIQUE SCAN | PK_TAB9 | 1 | | |
|* 23 | INDEX UNIQUE SCAN | PK_TAB10 | 1 | 13 | |
| 24 | BUFFER SORT | | 1 | 6 | 9 |
| 25 | TABLE ACCESS BY INDEX ROWID | TAB2 | 1 | 6 | 1 |
|* 26 | INDEX RANGE SCAN | TAB2_IDX2 | 1 | | |
|* 27 | TABLE ACCESS BY INDEX ROWID | TAB1 | 12 | 468 | 1 |
|* 28 | INDEX UNIQUE SCAN | PK_TAB1 | 1 | | |
Predicate Information (identified by operation id):
2 - filter(ROWNUM<=3)
10 - access("TAB5"."PATH_ID"="TAB4"."PATH_ID")
12 - filter("TAB3"."AUTH_GROUP_ID"<>(-1) AND ("TAB3"."AUTH_GROUP_ID"=0 OR "TAB3"."AUTH_GROUP_ID"=1))
13 - access("TAB3"."PATH_ID"="TAB4"."PATH_ID")
18 - access("TAB5"."DOMAIN_ID"="TAB6"."DOMAIN_ID")
19 - access("TAB6"."DOMAIN_ID"="TAB7"."DOMAIN_ID")
20 - access("TAB7"."RULE_ID"="TAB8"."RULE_ID")
22 - access("TAB9"."POLICY_ID"="TAB5"."POLICY_ID")
23 - access("TAB9"."ASSOCIATED_FORM_ID"="TAB10"."FORM_ID")
26 - access("TAB2"."CERT_SERIAL_NUM"=1022)
27 - filter("VIEW2"."POLICY_ID"="TAB1"."POLICY_ID")
28 - access("TAB1"."TRANSACTION_ID"="TAB2"."TRANSACTION_ID")
Note: cpu costing is off
52 rows selected.
Elapsed: 00:00:03.37
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COLLECTION ITERATOR (PICKLER FETCH) OF 'DISPLAY'
Statistics
38 recursive calls
0 db block gets
287 consistent gets
0 physical reads
0 redo size
5006 bytes sent via SQL*Net to client
405 bytes received via SQL*Net from client
5 SQL*Net roundtrips to/from client
29 sorts (memory)
0 sorts (disk)
52 rows processed -
ROWNUM can use with ORDER BY clause?
Hi
Following i have two quires in ROWNUM order for example..
1:query
select rownum,empno,ename,deptno from emp
where rownum <= 14;
result:
rownum empno ename deptno
1 7369 SMITH 20
2 7499 ALLEN 30
3 7521 WARD 30
4 7566 JONES 20
5 7654 MARTIN 30
6 7698 BLAKE 30
7 7782 CLARK 10
8 7788 SCOTT 20
9 7839 KING 10
10 7844 TURNER 30
11 7876 ADAMS 20
12 7900 JAMES 30
13 7902 FORD 20
14 7934 MILLER 10
2:Query , add ORDER BY clause it will change the sequence of ROWNUM.
select rownum,empno,ename,deptno from emp
where rownum <= 14
order by deptno;
result:
rownum empno ename deptno
7 7782 CLARK 10
9 7839 KING 10
14 7934 MILLER 10
1 7369 SMITH 20
11 7876 ADAMS 20
13 7902 FORD 20
8 7788 SCOTT 20
and so on......
but i want these records from 2 to 5...how i can query this through ROWNUM or any sequence because ORDER BY clause change the order of ROWNUM and i could get this result.
rownum empno ename deptno
9 7839 KING 10
14 7934 MILLER 10
1 7369 SMITH 20
11 7876 ADAMS 20
please send me general query which i can apply on any table.
advance thanks.My guess is that you are looking for a pagination solution. If so, here is a thread on Asktom:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:127412348064
So, essentially, you ORDER BY first and then write a wrapper to get your the rownum.
If you do it this way, You will also use the top-n optimization that Oracle uses.
Rahul. -
How to make an ORDER BY clause dynamic
is there anyway to make the ORDER BY clause in an SQL query within a DB control
dynamic? I have tried to pass a String of the column name and place it in the
statement within {}, but it doesn't work"Mark" <[email protected]> wrote:
>
is there anyway to make the ORDER BY clause in an SQL query within a
DB control
dynamic? I have tried to pass a String of the column name and place
it in the
statement within {}, but it doesn't workDid you find how ? please let me know, I also need to have a dynamic order by
clause. -
Hello,
I created a radio button to sort the data in the form.
STATIC2:Date Asc;1, Date Desc;2, Activity;3
The data is only sorted by date asc and activity asc. The sort by date desc didn't work.
ORDER BY DECODE(:P20010100_SORT,1,to_char(ENTRY_DT,'dd/mm/yyyy')|| 'Asc',2,to_char(ENTRY_DT,'dd/mm/yyyy')|| 'Desc',3,ACT_ID || 'Asc',to_char(entry_dt,'dd/mm/yyyy')|| 'Asc')
Do you have an idea how to do it ?
Thanks in advanceYou cant do order bys with ASC / DESC unless you dynamic sql or some trickery.
For example:
Make columns that reverse the values for you so that you are always sorting ASC.
order by decode(:somevar,
1,created,
2,to_date('01-jan-2999','dd-mon-yyyy')-(created)) -
What is the point in having multiple columns in ORDER BY clause?
DB version:10gR2
When using ORDER BY clause, the rows are always sorted according to the first column in the ORDER BY clause. So, what is point in having multiple columns in the ORDER BY clause(i always see this in production codes)?
For the below SQLs' from SCOTT schema, the result sets are always ordered according the first column ename. When i added job asc and job desc, the result set doesn't change.
SQL> select * from emp order by ename;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7839 KING PRESIDENT 17-NOV-81 5000 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
14 rows selected.
SQL> select * from emp order by ename, job;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7839 KING PRESIDENT 17-NOV-81 5000 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
14 rows selected.
SQL> select * from emp order by ename, job desc;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7839 KING PRESIDENT 17-NOV-81 5000 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7934 MILLER CLERK 7782 23-JAN-82 1300 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
14 rows selected.Because there is only one employee with the name SCOTT,FORD ...etc in the emp table and your first column in the order by list is ename
you spot the difference now
SQL> select * from emp order by job;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7788 SCOTT ANALYST 7566 19-APR-87 00:00:00 3000 20
7902 FORD ANALYST 7566 03-DEC-81 00:00:00 3000 20
7934 MILLER CLERK 7782 23-JAN-82 00:00:00 1300 10
7900 JAMES CLERK 7698 03-DEC-81 00:00:00 950 30
7369 SMITH CLERK 7902 17-DEC-80 00:00:00 800 20
7876 ADAMS CLERK 7788 23-MAY-87 00:00:00 1100 20
7698 BLAKE MANAGER 7839 01-MAY-81 00:00:00 2850 30
7566 JONES MANAGER 7839 02-APR-81 00:00:00 2975 20
7782 CLARK MANAGER 7839 09-JUN-81 00:00:00 2450 10
7839 KING PRESIDENT 17-NOV-81 00:00:00 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 00:00:00 1500 0 30
7654 MARTIN SALESMAN 7698 28-SEP-81 00:00:00 1250 1400 30
7521 WARD SALESMAN 7698 22-FEB-81 00:00:00 1250 500 30
7499 ALLEN SALESMAN 7698 20-FEB-81 00:00:00 1600 300 30
14 rows selected.
Elapsed: 00:00:00.00
SQL> select * from emp order by job, deptno asc;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7902 FORD ANALYST 7566 03-DEC-81 00:00:00 3000 20
7788 SCOTT ANALYST 7566 19-APR-87 00:00:00 3000 20
7934 MILLER CLERK 7782 23-JAN-82 00:00:00 1300 10
7369 SMITH CLERK 7902 17-DEC-80 00:00:00 800 20
7876 ADAMS CLERK 7788 23-MAY-87 00:00:00 1100 20
7900 JAMES CLERK 7698 03-DEC-81 00:00:00 950 30
7782 CLARK MANAGER 7839 09-JUN-81 00:00:00 2450 10
7566 JONES MANAGER 7839 02-APR-81 00:00:00 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 00:00:00 2850 30
7839 KING PRESIDENT 17-NOV-81 00:00:00 5000 10
7654 MARTIN SALESMAN 7698 28-SEP-81 00:00:00 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-81 00:00:00 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 00:00:00 1250 500 30
7499 ALLEN SALESMAN 7698 20-FEB-81 00:00:00 1600 300 30
14 rows selected.
Elapsed: 00:00:00.01
SQL> select * from emp order by job,deptno desc;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7902 FORD ANALYST 7566 03-DEC-81 00:00:00 3000 20
7788 SCOTT ANALYST 7566 19-APR-87 00:00:00 3000 20
7900 JAMES CLERK 7698 03-DEC-81 00:00:00 950 30
7369 SMITH CLERK 7902 17-DEC-80 00:00:00 800 20
7876 ADAMS CLERK 7788 23-MAY-87 00:00:00 1100 20
7934 MILLER CLERK 7782 23-JAN-82 00:00:00 1300 10
7698 BLAKE MANAGER 7839 01-MAY-81 00:00:00 2850 30
7566 JONES MANAGER 7839 02-APR-81 00:00:00 2975 20
7782 CLARK MANAGER 7839 09-JUN-81 00:00:00 2450 10
7839 KING PRESIDENT 17-NOV-81 00:00:00 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 00:00:00 1500 0 30
7654 MARTIN SALESMAN 7698 28-SEP-81 00:00:00 1250 1400 30
7521 WARD SALESMAN 7698 22-FEB-81 00:00:00 1250 500 30
7499 ALLEN SALESMAN 7698 20-FEB-81 00:00:00 1600 300 30
14 rows selected.
Elapsed: 00:00:00.01
SQL> -
How to sort random number without the used of order by
Hi ,
how should 5 random number be sorted without the use of order by in PLSQL
eg.
id amount
1 2
2 9
3 3
4 5
5 7
Edited by: sake1 on 1-dec-2010 8:16I used Altavista and found one example, how does it look?
DECLARE
/* there is no built array in oracle, you must declare
your own */
TYPE Numarray IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
/* the array of numbers - using assoc array because I can start
with zero like traditional arrays */
Nums Numarray;
n NUMBER := 0;
Temp NUMBER;
BEGIN
/* load up the array, put 20 random values in the array,
in array indicies 0 to 19 */
FOR i IN 0 .. 19
LOOP
Nums(i) := Round(Dbms_Random.Value(1, 1000));
END LOOP;
/* get the array size */
n := Nums.Count();
/* display the unsorted values - loop through the whole array and
print out the values */
Dbms_Output.Put_Line('unsorted:');
FOR i IN Nums.First .. Nums.Last LOOP
Dbms_Output.Put_Line(Nums(i));
END LOOP;
/* bubble sort - using two loops, compare each value with the one
after it
if the one after the current one is smaller , then
switch their locations in the array, this is just like standard
bubble sorts
in other languages. The only real diff is the syntax.
FOR i IN 0 .. n - 1 LOOP
FOR j IN 0 .. n - (i + 1) - 1 LOOP
IF (Nums(j) > Nums(j + 1)) THEN
Temp := Nums(j);
Nums(j) := Nums(j + 1);
Nums(j + 1) := Temp;
END IF;
END LOOP;
END LOOP;
/* display the values sorted */
Dbms_Output.Put_Line('sorted');
FOR i IN Nums.First .. Nums.Last LOOP
Dbms_Output.Put_Line(Chr(9) || Nums(i));
END LOOP;
END;
unsorted:
155
909
795
977
942
214
105
269
283
820
108
594
784
921
856
736
802
457
951
411
sorted
105
108
155
214
269
283
411
457
594
736
784
795
802
820
856
909
921
942
951
977
*/In the code the first comment is wrong actually i think, that one:
"there is no built array in oracle, you must declare your own"
I remember there were some system collection-types, if i'm not mixing with something, i remember there was some kind of such but they were un-documented ones, so we can juridically say that the comment in the code was still correct. -
JPQL - No UPPER() in ORDER BY clause??
I have created a NamedQuery and am attempting to order my returned collection using the ORDER BY clause, however, the specification asks for string ordering to be case insensitive. It seems that I cannot do that with the Java Persistence Query Language - or at least the implementation that we are using. I am using Glassfish v2ur2 with uses Oracle TopLink Essentials - 2.0.1, Build b04-fcs (found in my Exception message).
I suspect that the only way to do what I want is to create a Comparator for the ResultList and run a sort after I get the result list from my EntityManager. Is that correct or is my syntax wrong in my JPQL?
Here is my named query (cut from a larger list of named queries), pretty simple:
@NamedQuery(name = "MyObject.findAll", query = "SELECT a FROM MyObject a ORDER BY UPPER(a.myString), a.Id")Here is a summary exception report that I receive:
===========================================================================
Exception: javax.ejb.EJBException
Description: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException: null; nested exception is:
Exception [TOPLINK-8024] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.excepti
ons.EJBQLException
Exception Description: Syntax error parsing the query [MyObject.findAll: SELECT a FROM MyObject a WHERE ORDER BY UPPER(a.myString), a.Id], line 1, column 81: syntax error at [UPPER].
Internal Exception: line 1:81: expecting IDENT, found 'UPPER'
(Stack-Trace Included)
===========================================================================Post Author: krypton
CA Forum: Data Connectivity and SQL
Thanks Lynn
I tried your suggestion. But there is one probelm.
When i sort the data in descending order using the count(calls) field, the data is returned but the customer's name appears multiple times along with their calls raised.
E.g, if customer Mark raised multiple calls i.e. 2, 5, and 10 calls, then the report will show
Mark 2
Mark 5
Mark 10
But is there a way to aggregate all the calls for mark and show them only once:
such as Mark 17
Thanks -
Evaluate Expression in Order By Clause
Hi,
I'm having trouble to execute following JPQL.
Select r.firstname, r.lastname, (e.distance/e.duration) from Runner r Inner Join r.event e Order BY (e.distance/e.duration) Desc;
Error suggests that '(' character is unacceptable in Order By Clause. Here is the error.
javax.servlet.ServletException: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [Select r.firstname, r.lastname, (e.distance/e.duration) from Runner r Inner Join r.event e Order BY (e.distance/e.duration) Desc;], line 1, column 101: unexpected token [(].
Internal Exception: NoViableAltException(81!=[1328:1: orderByItem returns [Object node] : (n= stateFieldPathExpression (a= ASC | d= DESC | ) | i= IDENT (a= ASC | d= DESC | ) );])
Can someone please show me how to fix it.
Thanks,
AdamHello Adam
You cannot use "(e.distance/e.duration)" as an order by clause. The correct query would be:
"Select r.firstname, r.lastname, (e.distance/e.duration) as speed from Runner r Inner Join r.event e Order BY speed Desc"
but will not work until bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=331575 is fixed. Please vote for it.
Best Regards,
Chris -
Order By clause is ignoring LowerCase field name
I am trying to use a QoQ, but am running into a problem when
using the order by clause...
All the fieldvalues in the order by field start with
uppercase except for one, and this field name gets thrown to the
end of the list
Anyone got any ideas???
thanks
SujitBefore you try the following, please note that you can clean
this up in your original DB queries -- which is almost always
better.
Anyway, suppose your QofQ was:
SELECT MixcasedColumn
FROM SomeQuerySet
ORDER BY MixcasedColumn
Then you would add a dummy column to use for case-insensitive
sort:
SELECT
MixcasedColumn, UPPER (MixcasedColumn) AS SortColumn
FROM
SomeQuerySet
ORDER BY
SortColumn <!--- Note that upper() is not allowed here
but derived columns are! ---> -
Hi all,
I'm creating a webpage using jsp thats accessing a mysql database. When I get a ResultSet from a query, I was wondering if anyone could give me some pointers on how I could sort the results based on a field name that someone clicks on. For example:
Column1 Column2
5 2
8 1
3 6I'd like to create hyperlinks on the field names so when a user clicks on it, it will sort the data in according to that field. Here is my code that I am trying to modify:
public String displayResultSet(ResultSet rs)
{// return a result set as an html table
String htmlTable = "";
try {
// get the number of columns
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
// create a table and display the mysql field names as table headers
htmlTable += "<TABLE>\n<TR>\n";
for(int i=1; i<=numColumns; i++)
htmlTable += "<TH>" + rsmd.getColumnName(i) + "</TH>\n";
htmlTable += "</TR>\n\n";
// create an object to temporarily hold a piece of ResultSet data
Object cellData = null;
// display the data in the ResultSet in rows of an html table
while(rs.next())
{// while the ResultSet has more rows, convert them to html
htmlTable += "<TR>";
for(int j=1; j<=numColumns; j++)
{// if the data is not null, display it, otherwise display a blank space
cellData = rs.getObject(j);
if(cellData != null)
htmlTable += "<TD>" + rs.getObject(j) + "</TD>\n";
else
htmlTable += "<TD> </TD>\n";
htmlTable += "</TR>\n\n";
htmlTable += "</TABLE>\n\n";
catch (Exception e)
{ return("Error accessing database: " + e); }
return htmlTable;
}Any help or references to where I can read up on it would be appreciated. Thanks
LeonYour display code should not be mixed in with your database code. That functionality should be seperated classes.
Generally GUIs do the ordering themselves. They do not repeatedly call the database.
But if you want you pass in a descriptor that defines the fields that will be ordered on. You optionally map that to the exact database field names. You then use StringBuilder to construct the entire SQL string and add the order by clause dynamically at the end. Then you execute it. -
Sorting a column does not result in distinct values on Dashboard prompts
Hi,
We have a period column, the records of which are 'JAN-02' , "FEB-02"...."DEC-09". We need sort this column in descending order in Dashboard Prompts. We have another column "Date", which has been used to sort the period column. To achieve this in descending order, we have converted Show Results from “All Values” to “SQL Results” in dashboard prmpts, then entered the below sql.
SELECT "CODE COMBINATIONS"."LINE AC PERIOD" FROM INVOICE_PAYMENTS
order by "CODE COMBINATIONS"."LINE AC DATE" desc
The above sql resulted in non-distinct values as below. Using distinct in the above sql throws syntax error.
Period
JAN-09
JAN-09
JAN-09
FEB-09
FEB-09
How do we get distinct values and in descending order??
Thanks and appreciate any ideas
SuryaGo to advanced tab and check "Use distinct clause" that will fire a distinct to the query.
In the rpd month logical column , there is an option called sort order in the general properties and you need to specify the date column if you need to sort it based on the date column and in the Answers you can simply enable Descending sort order on the same column. That should take care of it
Hope it helps
Thanks
Prash
Maybe you are looking for
-
Firewire external mobil disk hard drive is no longer recognized
After last system update, my firewire external mobil disk hard drive is no longer recognized. Any solutions? Why does MacOS go backwards... gets worse over time?
-
Playlists will not sync with Windows PC
My playlist in iTunes will not sync with my ipod Touch. any ideas?
-
Wanted to confirm my understaing for ABAP and JAVA mapping. Am I correct in my assumption that these mapping techniques can be used only if input and ouput is in XML format ? So if XI is receiving a flat comma separated text/non-XML file or an IDOC f
-
Filtering system.log & console.loog
I have a few problems which I have been trying to find in console.log & system.log I have a couple of applications which write a lot of entries here, which makes it very difficult to read. Is it possible to filter events in console.log - saying for e
-
Asset Posted Wrongly to Another Asset
Hi My user have posted one Non-PO Asset posting into the SAP system, but realized that the Asset No. posted wrongly in last month (Nov 06) and depreciation had been done. Please suggest whether I can reverse and repost to the correct Asset No. & what