Help: PL/SQL passing paramter to ORDER BY clause
I am working on a procedure that using a parameter to pass sorting order. If there parameter, say p_order which is varchar2, can I just use the it directly passing the field name to the order by clause?
What I really want to know is that do I have to use decode together with p_order to achieve the goal?
WJH
Hi,
The positional notaion in ORDER BY, e.g.
ORDER BY 2, 1is one of the rare cases in which a numeric literal is required. Using an expression, even a bind variable, won't raise an error, but won't sort, either. (It's equivalent to sorting by a constant, which doesn't sort at all.)
Like Centinul said, you have to use dynamic SQL to construct the ORDER BY clause, or use some kind of IF-THEN-ELSE logic (such as CASE), like this:
SELECT ename, sal
FROM scott.emp
ORDER BY CASE
WHEN :x = 1 THEN ename
ELSE TO_CHAR (sal, '000000')
END;
Similar Messages
-
Passing parameters in order by clause of cursor
Hi friends,
I am facing a strange problem
I have a cursor with a order by clause.
OPEN cursor_nomrpt FOR
SELECT DISTINCT
CAST(plano.desc3 AS VARCHAR2(50)) category
,plano.name plan_name
,nvl(CAST(plano.desc6 AS VARCHAR2(50)),'not applicable') pcrr
,nvl(trunc(plano.value18,2),0) nominal_slm
,nvl(trunc(plano.value19,2),0) blm
,plano.dbdateeffectivefrom date_live
plano.dbkey pog_id
,case when plano.value47 < 0 THEN 0 when plano.value47 IS NULL THEN 0 ELSE plano.value47 END AS parent_id
FROM
dplapro1.ix_spc_planogram plano
INNER JOIN dplapro1.ix_spc_performance perf ON plano.dbkey = perf.dbparentplanogramkey
INNER JOIN dplapro1.ix_spc_product product ON perf.dbparentproductkey = product.dbkey
INNER JOIN dplapro1.ix_spc_product_key prodkey ON product.dbkey2 = prodkey.dbkey
AND prodkey.keylevel = 2
WHERE
plano.value50 = 0
AND plano.dbkey4 = p_subcatkey
ORDER BY ltrim(rtrim(p_orderby)) ASC;
p_orderby is the parameter being passed. But the output is not sorted. But when I run the cursor by hardcoding the parameter value it works fine...
Need your help on thisHi,
When you use a local variable in a cursor, it's as if you had hard-coded a literal in its place, so you can't use a variable for a column name.
If you know all the possible values of p_orderby, you can do something like this:
ORDER BY TRIM ( CASE p_orderby
WHEN 'DESC' THEN plano.desc
WHEN 'VALUE' THEN plano.value
END
) ASC;If you don't know all the possible values, you could use dynamic SQL.
By the way,
TRIM (x)returns the same results as
LTRIM ( RTRIM (x)) -
SQL Query rewrite, remove ORDER BY clause
Hello,
we've just installed a proprietary application which uses an Oracle 11.2.0.2 RAC database. We've seen that one of the auto-generated application's queries
has poor performance (3-5 minutes for results), the query does a SELECT and at the end it uses an ORDER BY clause. If we remove the ORDER BY clause
the query returns the results in less than 5 seconds. Unfortunately, we can't re-write the query in the application since we don't have any access to it and
i was wondering if there is a way to rewrite the specific query from the database.
We've already seen the SQL Patch but we can change only the hints of the query so we can't remove the ORDER BY clause from it. From what we've seen
outlines also change only the hints and not the actual sql statement.
Is there a way to rewrite the specific query from the database ?
thanks in advance,
GiannisMaybe DBMS_ADVANCED_REWRITE can help but this a SQL question than has very likely nothing to do with RAC.
See http://www.oracle-base.com/articles/10g/dbms_advanced_rewrite.php. -
Sql count function in order by clause
Post Author: krypton
CA Forum: Data Connectivity and SQL
Hi Guys
Can i ask a quick question. I am trying to retrieve data remotely from a SQL Server via crystal reports.
Within the Database Expert I have entered a SQL query to retrive the number of (call center) support calls raised by our customers:-
Select `Primary_Company`, COUNT(`Calls`)From `SPRT_Issue` GROUP BY `Primary_Company`ORDER BY COUNT(`Calls`) desc
The customer's column is called 'Primary Company' and the calls they raise are in the 'Calls' column. the above is a normal sql query.
However Crystal fails to run the query and generates an error message :-
Failed to open a rowset. Details: 420: Driver] Expected lexical element not found: <identifier>
I dont understand why it wont run. In the ORDER BY clause if i replace field 'Calls' by the field 'Primary Company' then it works.
I think the problem is that it wont accept the count function in the order by clause. which is what i want it to do i.e display the calls in descending order by each customer.
Could someone tell me if there is a way around it.
Thanks
KryptonPost 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 -
Problem in sql query because of order by clause
Hi All,
I am facing a one problem in my one sql query.I am using Oracle 10gR2.
Query is given below:
SELECT t1.ename
FROM T1, T2
WHERE T1.EMPNO = 1234
AND T1.ACCOUNTNO = T2.ACCOUNTNO
AND T1.SEQ = T2.SEQ
ORDER BY T2.SEQThe Plan of the query is :
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 2 | 218 | 11716 (1)| 00:00:41 |
|* 1 | TABLE ACCESS BY INDEX ROWID | T1 | 1 | 89 | 1 (0)| 00:00:01 |
| 2 | NESTED LOOPS | | 2 | 218 | 11716 (1)| 00:00:41 |
|* 3 | TABLE ACCESS BY INDEX ROWID| T2 | 2 | 40 | 11715 (1)| 00:00:41 |
| 4 | INDEX FULL SCAN | PK_T2_SEQ | 58752 | | 122 (5)| 00:00:01 |
|* 5 | INDEX RANGE SCAN | FK_ACCOUNTNO | 3 | | 0 (0)| 00:00:01 |
----------------------------------------------------------------------------------------------------Now i want to reduce the time of this query.
If i am removing Order by clause from query than performance of the query is totally perfect but with order by clause its taking a time.
I have already set SORT_AREA_SIZE but still nothing is improving.
Welcome and thanks for your suggestions.
Thanks,
Edited by: BluShadow on 23-Jun-2011 07:55
added {noformat}{noformat} tags and formatted explain plan to make it readable. Please see {message:id=9360002} for details on how to post code and dataHi,
There are a couple of things I do not understand.
1. Why don't you put {noformat}{noformat} around your code, it makes it so much easier to read, especially your explain plan
2. You claim that the ORDER BY is problematic compared to no order by. Then why do you choose to post only one plan?
3. It is hard to understand how your tables relate, and which indexes you have and which you don't.
- PK_T2_SEQ, does this mean that SEQ alone is primary key of T2?
- If SEQ is primary key of T2, why do you join on accountno, seq and not just seq?
- If SEQ is primary key of T2 one of the tables is denormalized.
4. FK_ACCOUNTNO, is this an index on accountno, alone?
- Or is this AccountNo, Seq?
5. Is there no index on T1.EMPNO?
Above could of course just be a case of my not understanding the names of your indexes.
So, here are my guesses:
Above plan is for the ORDER BY query. That means the optimizer, has chosen to full scan PK_T2_SEQ, since data is then read according to the ORDER BY.
(This could be a bad choice)I
You could try and order by t1.seq, instead. Result should be the same.
Regards
Peter -
Is passing parameter to ORDER BY clause possible?
I'm using a function to return a ref cursor and currently pass a parameter without any problems. I would like to change the sort on the fly by passing a parameter to the order by clause, but Oracle ignores it.
CREATE OR REPLACE PACKAGE pkg_agent_appt_status AS
TYPE rcur IS REF CURSOR;
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2) RETURN rcur;
END pkg_agent_appt_status;
CREATE OR REPLACE PACKAGE BODY pkg_agent_appt_status AS
FUNCTION f_agent_appt_status (ssn IN VARCHAR2, sort_str IN VARCHAR2)
RETURN rcur
IS
retval rcur;
BEGIN
OPEN retval FOR
SELECT agncy.CORPORATE_NAME "Agency Name",
agnt_state.APPT_STATE "State",
agnt.AGENT_STATUS "Appt Status",
TO_CHAR(agnt_state.APPT_STATE_EFF_DT,'mm/dd/yyyy') "Effective Date",
agnt.AGENT_NUMBER "Agent ID",
agnt.AGENT_STATUS "Agent Status",
STATE.STATE_NAME
FROM AGNT_APPT_STAT_PRDCR_WRK agnt,
AGNT_APPT_STAT_WRK agncy,
AGNT_APPT_STATE_STAT_PRDCR_WRK agnt_state,
STATE
WHERE agnt.AGENT_TAX_ID = ssn
AND agnt.COMPANY_CODE = agncy.COMPANY_CODE
AND agnt.PARENT_AGENT_AGENCY_ID = agncy.AGENT_NUMBER
AND agnt.COMPANY_CODE = agnt_state.COMPANY_CODE
AND agnt.AGENT_AGENCY_ID = agnt_state.AGENT_AGENCY_ID
AND agnt.AGENT_NUMBER = agnt_state.AGENT_NUMBER
AND agnt_state.APPT_STATE = STATE.STATE_CODE
ORDER BY
sort_str;
RETURN retval;
END f_agent_appt_status;
END pkg_agent_appt_status;This is quite easy, as you are already using a REF CURSOR. Instead of
OPEN retval FOR
SELECT ...
ORDER BY sort_str;we can code this:
OPEN retval FOR
'SELECT ...
ORDER BY '|| sort_str;Watch out for the single quotes in your query e.g. the date format mask: you need to wrap these in an additional set of single quotes i.e. 'mm/dd/yyyy' becomes ''mm/dd/yyyy''.
Cheers, APC -
[10g] Complex Order By clause...
I can manually sort my data, and can provide the logic I use to do that, but I need help actually putting it into an order by clause.
I am working in XE, 10g...
Here's some sample data to start with:
CREATE TABLE inventory_history
( time_stamp CHAR(20)
, part_nbr CHAR(25)
, act_date DATE
, ord_nbr CHAR(10)
, ln_nbr CHAR(3)
, code_pre CHAR(3)
, code_sfx CHAR(3)
, user_id CHAR(36)
, qty NUMBER(15,4)
, adj_qty NUMBER(15,4)
, cnt_qty NUMBER(15,4)
INSERT INTO inventory_history
VALUES ('20080716100442488094','N174X53A',TO_DATE('07/16/2008','mm/dd/yyyy'),NULL,NULL,'MTL','INS','user2',0,0,31);
INSERT INTO inventory_history
VALUES ('20080717135714597592','N174X53A',TO_DATE('07/17/2008','mm/dd/yyyy'),NULL,NULL,'MTL','INS','user2',31,0,0);
INSERT INTO inventory_history
VALUES ('20100401145927954563','N174X53A',TO_DATE('04/01/2010','mm/dd/yyyy'),NULL,NULL,'MTL','INS','user1',0,0,31);
INSERT INTO inventory_history
VALUES ('20100917085814607499','N174X53A',TO_DATE('09/17/2010','mm/dd/yyyy'),NULL,NULL,'MTL','INS','user1',30,0,0);
INSERT INTO inventory_history
VALUES ('20080715093021657035','N174X53A',TO_DATE('07/15/2008','mm/dd/yyyy'),'P000012345','001','POR','LIN','user5',31,0,0);
INSERT INTO inventory_history
VALUES ('20080716100406218646','N174X53A',TO_DATE('07/16/2008','mm/dd/yyyy'),'P000012345','001','MTL','INS','user2',31,0,0);
INSERT INTO inventory_history
VALUES ('20080819111303812239','N174X53A',TO_DATE('08/19/2008','mm/dd/yyyy'),'P000012345','002','POR','LIN','user5',31,0,0);
INSERT INTO inventory_history
VALUES ('20100504083427334677','N174X53A',TO_DATE('05/04/2010','mm/dd/yyyy'),'P000012345','002','POR','RTV','user3',31,0,0);
INSERT INTO inventory_history
VALUES ('20100512095750285578','N174X53A',TO_DATE('05/12/2010','mm/dd/yyyy'),'P000012345','002','POR','LIN','user6',30,0,0);
INSERT INTO inventory_history
VALUES ('20100614130143734676','N174X53A',TO_DATE('06/14/2010','mm/dd/yyyy'),'P000012345','002','MTL','INS','user1',0,0,30);
INSERT INTO inventory_history
VALUES ('20100412101824624708','N174X53A',TO_DATE('04/12/2010','mm/dd/yyyy'),'P000012345','004','POR','LIN','user4',31,0,0);
INSERT INTO inventory_history
VALUES ('20100422150057876187','N174X53A',TO_DATE('04/22/2010','mm/dd/yyyy'),'P000012345','004','MTL','INS','user2',0,0,31);
INSERT INTO inventory_history
VALUES ('20100504081750020711','N174X53A',TO_DATE('05/04/2010','mm/dd/yyyy'),'P000012345','004','POR','RTV','user3',31,0,0);
INSERT INTO inventory_history
VALUES ('20100512095303832580','N174X53A',TO_DATE('05/12/2010','mm/dd/yyyy'),'P000012345','004','POR','LIN','user6',31,0,0);
INSERT INTO inventory_history
VALUES ('20100712133833381506','N174X53A',TO_DATE('07/12/2010','mm/dd/yyyy'),'P000012345','004','MTL','INS','user1',31,0,0);
INSERT INTO inventory_history
VALUES ('20091124130834762244','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),'P000045557','002','POR','LIN','user12',10,0,0);
INSERT INTO inventory_history
VALUES ('20091124131110241744','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),'P000045557','002','POR','ADJ','user12',0,10,0);
INSERT INTO inventory_history
VALUES ('20091124131850641554','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),'P000045557','002','POR','ADJ','user12',0,-20,0);
INSERT INTO inventory_history
VALUES ('20091124131916249134','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),'P000045557','002','POR','LIN','user12',10,0,0);
INSERT INTO inventory_history
VALUES ('20091124135601215291','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),'P000045557','002','POR','ADJ','user12',0,10,0);
INSERT INTO inventory_history
VALUES ('20091124140318980761','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),NULL,NULL,'MTL','INS','user13',10,0,0);
INSERT INTO inventory_history
VALUES ('20091124142344235001','015-279A',TO_DATE('11/24/2009','mm/dd/yyyy'),'P000045557','002','POR','ADJ','user12',0,-10,0);
INSERT INTO inventory_history
VALUES ('20100701123833300000','test',TO_DATE('07/01/2010','mm/dd/yyyy'),'P000011111','001','POR','LIN','user12',5,0,0);
INSERT INTO inventory_history
VALUES ('20100705964833300000','test',TO_DATE('07/05/2010','mm/dd/yyyy'),'P000011111','001','MTL','INS','user2',5,0,0);
INSERT INTO inventory_history
VALUES ('20100702123456700000','test',TO_DATE('07/02/2010','mm/dd/yyyy'),'P000011111','002','POR','LIN','user6',5,0,0);
INSERT INTO inventory_history
VALUES ('20100704987654300000','test',TO_DATE('07/04/2010','mm/dd/yyyy'),NULL,NULL,'MTL','INS','user1',5,0,0);And this is what I'm looking to do ... this is how I want the above data sorted:
TIME_STAMP PART_NBR ACT_DATE ORD_NBR LN_NBR CODE_PRE CODE_SFX USER_ID QTY ADJ_QTY CNT_QTY
20091124130834762244 015-279A 11/24/2009 P000045557 002 POR LIN user12 10 0 0
20091124131110241744 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 10 0
20091124131850641554 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 -20 0
20091124131916249134 015-279A 11/24/2009 P000045557 002 POR LIN user12 10 0 0
20091124135601215291 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 10 0
20091124140318980761 015-279A 11/24/2009 MTL INS user13 10 0 0
20091124142344235001 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 -10 0
20080715093021657035 N174X53A 7/15/2008 P000012345 001 POR LIN user5 31 0 0
20080716100406218646 N174X53A 7/16/2008 P000012345 001 MTL INS user2 31 0 0
20080716100442488094 N174X53A 7/16/2008 MTL INS user2 0 0 31
20080717135714597592 N174X53A 7/17/2008 MTL INS user2 31 0 0
20080819111303812239 N174X53A 8/19/2008 P000012345 002 POR LIN user5 31 0 0
20100401145927954563 N174X53A 4/1/2010 MTL INS user1 0 0 31
20100512095750285578 N174X53A 5/12/2010 P000012345 002 POR LIN user6 30 0 0
20100614130143734676 N174X53A 6/14/2010 P000012345 002 MTL INS user1 0 0 30
20100412101824624708 N174X53A 4/12/2010 P000012345 004 POR LIN user4 31 0 0
20100422150057876187 N174X53A 4/22/2010 P000012345 004 MTL INS user2 0 0 31
20100512095303832580 N174X53A 5/12/2010 P000012345 004 POR LIN user6 31 0 0
20100712133833381506 N174X53A 7/12/2010 P000012345 004 MTL INS user1 31 0 0
20100917085814607499 N174X53A 9/17/2010 MTL INS user1 30 0 0
20100701123833300000 test 7/1/2010 P000011111 001 POR LIN user12 5 0 0
20100705964833300000 test 7/5/2010 P000011111 001 MTL INS user2 5 0 0
20100702123456700000 test 7/2/2010 P000011111 002 POR LIN user6 5 0 0
20100704987654300000 test 7/4/2010 MTL INS user1 5 0 0This is the logic I use to sort the data manually:
If the record has ord_nbr/ln_nbr (they aren't NULL), then sort by part_nbr, ord_nbr, ln_nbr, and time_stamp, in that order.
And here's the complicated part...
If the record does not have ord_nbr/ln_nbr (they are NULL, and this can only happen on MTL-INS transactions), then it needs to be placed into the sort I just described via this logic:
It must be placed with the other records with the same part_nbr, after the closest previous POR LIN transaction by time_stamp (for that part_nbr), but before the next chronological MTL-INS transaction by time_stamp (for that part_nbr), and between those 2 constraints, fit in by time_stamp.
Any suggestions??
Edited by: user11033437 on Sep 23, 2010 3:13 PM (Fixed order of sample data, so part_nbr was ascending, though really the overall sort doesn't matter, just the sorting within each part_nbr group.)Hi,
user11033437 wrote:
... And this is what I'm looking to do ... this is how I want the above data sorted:
TIME_STAMP PART_NBR ACT_DATE ORD_NBR LN_NBR CODE_PRE CODE_SFX USER_ID QTY ADJ_QTY CNT_QTY
20091124130834762244 015-279A 11/24/2009 P000045557 002 POR LIN user12 10 0 0
20091124131110241744 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 10 0
20091124131850641554 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 -20 0
20091124131916249134 015-279A 11/24/2009 P000045557 002 POR LIN user12 10 0 0
20091124135601215291 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 10 0
20091124140318980761 015-279A 11/24/2009 MTL INS user13 10 0 0
20091124142344235001 015-279A 11/24/2009 P000045557 002 POR ADJ user12 0 -10 0
20080715093021657035 N174X53A 7/15/2008 P000012345 001 POR LIN user5 31 0 0
20080716100406218646 N174X53A 7/16/2008 P000012345 001 MTL INS user2 31 0 0
20080716100442488094 N174X53A 7/16/2008 MTL INS user2 0 0 31
20080717135714597592 N174X53A 7/17/2008 MTL INS user2 31 0 0
20080819111303812239 N174X53A 8/19/2008 P000012345 002 POR LIN user5 31 0 0
20100401145927954563 N174X53A 4/1/2010 MTL INS user1 0 0 31
20100512095750285578 N174X53A 5/12/2010 P000012345 002 POR LIN user6 30 0 0
20100614130143734676 N174X53A 6/14/2010 P000012345 002 MTL INS user1 0 0 30
20100412101824624708 N174X53A 4/12/2010 P000012345 004 POR LIN user4 31 0 0
20100422150057876187 N174X53A 4/22/2010 P000012345 004 MTL INS user2 0 0 31
20100512095303832580 N174X53A 5/12/2010 P000012345 004 POR LIN user6 31 0 0
20100712133833381506 N174X53A 7/12/2010 P000012345 004 MTL INS user1 31 0 0
20100917085814607499 N174X53A 9/17/2010 MTL INS user1 30 0 0
20100701123833300000 test 7/1/2010 P000011111 001 POR LIN user12 5 0 0
20100705964833300000 test 7/5/2010 P000011111 001 MTL INS user2 5 0 0
20100702123456700000 test 7/2/2010 P000011111 002 POR LIN user6 5 0 0
20100704987654300000 test 7/4/2010 MTL INS user1 5 0 0This is the logic I use to sort the data manually:
If the record has ord_nbr/ln_nbr (they aren't NULL), then sort by part_nbr, ord_nbr, ln_nbr, and time_stamp, in that order.
And here's the complicated part...
If the record does not have ord_nbr/ln_nbr (they are NULL, and this can only happen on MTL-INS transactions), then it needs to be placed into the sort I just described via this logic:
It must be placed with the other records with the same part_nbr, after the closest previous POR LIN transaction by time_stamp (for that part_nbr), but before the next chronological MTL-INS transaction by time_stamp (for that part_nbr), and between those 2 constraints, fit in by time_stamp.Sorry, I don't see how you get those results from that data.
In normal string stort order '015-279A' comes before 'N174X53A', which comes before 'test'. How do you get the order you want?
Then within each part_nbr, your explanation seems to say you want the rows with NULL ord_nbr to come right after the preceding POR-LIN row (where "preceding" means according to time_stamp), which would result in this order:
TIME_STAMP PART_NBR ACT_DATE ORD_NBR LN_ COD
20091124130834762244 015-279A 11/24/2009 P000045557 002 POR
20091124131110241744 015-279A 11/24/2009 P000045557 002 POR
20091124131850641554 015-279A 11/24/2009 P000045557 002 POR
20091124131916249134 015-279A 11/24/2009 P000045557 002 POR
20091124140318980761 015-279A 11/24/2009 MTL
20091124135601215291 015-279A 11/24/2009 P000045557 002 POR
20091124142344235001 015-279A 11/24/2009 P000045557 002 POR
20080715093021657035 N174X53A 7/15/2008 P000012345 001 POR
20080716100442488094 N174X53A 7/16/2008 MTL
20080717135714597592 N174X53A 7/17/2008 MTL
20080716100406218646 N174X53A 7/16/2008 P000012345 001 MTL
20080819111303812239 N174X53A 8/19/2008 P000012345 002 POR
20100401145927954563 N174X53A 4/1/2010 MTL
20100504083427334677 N174X53A 5/4/2010 P000012345 002 POR
20100512095750285578 N174X53A 5/12/2010 P000012345 002 POR
20100917085814607499 N174X53A 9/17/2010 MTL
20100614130143734676 N174X53A 6/14/2010 P000012345 002 MTL
20100412101824624708 N174X53A 4/12/2010 P000012345 004 POR
20100422150057876187 N174X53A 4/22/2010 P000012345 004 MTL
20100504081750020711 N174X53A 5/4/2010 P000012345 004 POR
20100512095303832580 N174X53A 5/12/2010 P000012345 004 POR
20100712133833381506 N174X53A 7/12/2010 P000012345 004 MTL
20100701123833300000 test 7/1/2010 P000011111 001 POR
20100705964833300000 test 7/5/2010 P000011111 001 MTL
20100702123456700000 test 7/2/2010 P000011111 002 POR
20100704987654300000 test 7/4/2010 MTLCan you explain the sorting rules agian, using different words.
Explain in particular why the rows that are in the wrong place above should be changed.
The code I used to get the results above was:
WITH got_r_num AS
SELECT time_stamp
, part_nbr
, act_date
, ord_nbr
, ln_nbr
, code_pre
, code_sfx
, ROW_NUMBER () OVER ( PARTITION BY part_nbr
ORDER BY ord_nbr
, ln_nbr
, time_stamp
) AS r_num
FROM inventory_history
SELECT time_stamp
, part_nbr
, act_date
, ord_nbr
, ln_nbr
, code_pre
FROM got_r_num
ORDER BY part_nbr
, CASE
WHEN ord_nbr IS NOT NULL
THEN r_num
ELSE LAST_VALUE ( CASE
WHEN code_pre = 'POR'
AND code_sfx = 'LIN'
THEN r_num
END
IGNORE NULLS
) OVER ( PARTITION BY part_nbr
ORDER BY time_stamp
END
, r_num
;It's a good thing that you're using Oracle 10; earlier versions didn't have the IGNORE NULLS feature in LAST_VALUE. That can be worked around, but it's complicated, and this is complicated enough already.
By the way, if you want to experiment with this kind of ORDER BY expression, I suggest you iput it in the SELECT clause, like this:
WITH got_r_num AS
SELECT time_stamp
, part_nbr
, act_date
, ord_nbr
, ln_nbr
, code_pre
, code_sfx
, ROW_NUMBER () OVER ( PARTITION BY part_nbr
ORDER BY ord_nbr
, ln_nbr
, time_stamp
) AS r_num
FROM inventory_history
SELECT time_stamp
, part_nbr
, act_date
, ord_nbr
, ln_nbr
, code_pre
, code_sfx
, CASE
WHEN ord_nbr IS NOT NULL
THEN r_num
ELSE LAST_VALUE ( CASE
WHEN code_pre = 'POR'
AND code_sfx = 'LIN'
THEN r_num
END
IGNORE NULLS
) OVER ( PARTITION BY part_nbr
ORDER BY time_stamp
END
as O_NUM
, r_num
FROM got_r_num
ORDER BY part_nbr
, o_num
, r_num
;Edited by: Frank Kulash on Sep 23, 2010 5:39 PM
Sorry, I left off some columns of output. I'll fix it when I have time, which is not now. -
Problem in a inner query- order by clause
hi...
I have a update statement with a simple select clause present as inner query..
(select col1 from table1 where col2='abc' and rownum=1 order by col3 desc)
since it is a inner query, thats why i can not remove the brackets.
col3 may be 0 or 1(1 can occur only once...0 can be multiple times)
my target is to fetch the record if the col3 is 1
if it is not 1, then it will fetch the first record with col3=0...thats why i have put order by col3.
moreover i want only one record, thats why i have put rownum=1.
but it is failing with 'missing right parenthesis'.
please help..Hi,
Remember that the ORDER BY clause is applied last, after the WHERE clause is completed, so when you way
WHERE ROWNUM = 1
ORDER BY col3 DESCin the same sub-query, you're picking one row (arbitrarily), and then "sorting" that one row.
Here's one way to get the results you want:
SELECT col1
FROM (
SELECT col1
, ROW_NUMBER () OVER (ORDER BY col3 DESC)
AS r_num
FROM table1
WHERE col2 = 'abc'
AND col3 IN (0, 1)
WHERE r_num = 1
)Depending on how this is used in your complete query, there may be better ways to get the same results. -
TestStand Open SQL Statement does not support SQL's ORDER BY clause???
TestStand 1.0.3
Windows 2000 SP1
SQL Server 2000 Personal
You've got to be kidding me...
It appears that the built-in TestStand Open SQL Step does NOT support the
"ORDER BY" clause in the SELECT statement, even though the documentation
says it does. Is this true?
I have an Open SQL Statement query:
"SELECT * FROM [MyTable] WHERE ([Batch ID]=1234)"
it works fine, returning a correct record count 120 records. If I change
the Open SQL Statement query simply by adding an ORDER BY clause, such as:
"SELECT * FROM [MyTable] WHERE ([Batch ID]=1234) ORDER BY [MyField] ASC"
it returns a record count of zero. I know that "MyField" exists in the
MyTable table and contains valid data. The
second query works fine in SQL
Server Enterprise Manager.
Am I missing something? Is it true that the TestStand Open SQL Step does
NOT support the "ORDER BY" clause? If not, what &#$!ing good is it and why
does the manual state it is supported? Is there any other way using just
the TestStand steps to order a database recordset on one or more fields?
Any help would be appreciated.
Grrrrr....
Bob Rafuse
Etec Inc.> Bob -
> The database step types do not do anything special to the SQL command
> that you give it. The step just passes the command to the ADO
> provider. I tried a simple query using the step types with the
> following command,
>
> "SELECT UUT_RESULT.* FROM UUT_RESULT WHERE ([UUT_SERIAL_NUMBER] =
> 12345) ORDER BY [EXECUTION_TIME] ASC"
>
> and this return the expected results and the record count parameter
> was as expected. I tried this on TS 1.0.2 and TS 2.0 with MS Access
> 2000 and MS SQL Server 7.0. I do not have MS SQL Server 2000 at this
> time.
>
> It would be surprised if the step types are messing something up.
I've been doing some experimenting over the past couple of days. Simple,
one-table queries seem to handle the ORDER BY clause fine. Th
ings seem to
get messed up when I try multi-table queries with ORDER BY clause with the
TestStand database steps. I get no errors but the returned record counts
are always 0 with the ORDER BY and positive without the ORDER BY. The exact
same queries work fine in Visual Basic/ADO and the SQL Server Query
Analyzer.
> Questions:
> 1. Have you verified whether the data is actually returned even though
> the record count is zero?
Hmmm... yes data IS getting returned (at least on the two instances I just
checked), but the record count is always zero. I was not proceeding with
processing if the record count was 0.
Still... I don't know how to loop through the recordset without knowing how
many records there are an not eventually generate an error by passing EOF.
Is there another way using the TestStand database steps to determine a) the
number of records in the recordset or b) when I'm at EOF?
> 2. Are you using any advanced options on the Opend SQL Statement step
> type, specifically
the cursor type set to forward only? Forward only
> cursors do not allow for record counts.
Everything on the Advanced tab of the Open SQL Statement step is set to "Use
Default".
Bob. -
Need help in SQL (DENSE_RANK) function
Hello All,
I need the help in SQL.
We have a table called status and the column are
status_id number
account_id number
status_cd varchar2(10)
created_id varchar2(10)
created_by date
and data is as follows
insert into status values (1,101,'ENTER','ABC',to_date('21-JAN-2007 11:15:14','DD-MON-YYYY HH:MI:SS'));
insert into status values (2,101,'REVIEW','DEF',to_date('21-JAN-2007 11:30:25','DD-MON-YYYY HH:MI:SS'));
insert into status values (3,101,'APPROVE','GHI',to_date('21-JAN-2007 11:30:25','DD-MON-YYYY HH:MI:SS'));
insert into status values (4,102,'ENTER','ABC',to_date('21-JAN-2007 11:18:14','DD-MON-YYYY HH:MI:SS'));
insert into status values (5,102,'REVIEW','DEF',to_date('21-JAN-2007 11:33:25','DD-MON-YYYY HH:MI:SS'));
insert into status values (6,102,'CANCEL','GHI',to_date('21-JAN-2007 11:33:25','DD-MON-YYYY HH:MI:SS'));
insert into status values (7,103,'ENTER','ABC',to_date('21-JAN-2007 11:21:14','DD-MON-YYYY HH:MI:SS'));We have different status as follows
1. ENTER
2. REVIEW
3. APPROVE
4. CANCEL
5. REJECT
My requirement ..
I need the max of created_id column for the status in ('APPROVE','CANCEL') and if there is no status in ('APPROVE','REVIEW') than it should be NULL.
I wrote an SQL as
select account_id,max(created_id) keep (dense_rank first order by decode(status_cd,'APPROVE',created_dt,'REVIEW',created_dt,NULL) DESC NULLS LAST,
decode(status_cd,'APPROVE',status_id,'REVIEW',status_id,NULL) DESC NULLS LAST) last_app_rev_user
from status
group by account_id and gives me the output like
ACCOUNT_ID LAST_APP_R
101 GHI
102 DEF
103 ABCBut I want the Output like
ACCOUNT_ID LAST_APP_R
101 GHI
102 DEF
103 NULLAs the account 103 has no status called 'REVIEW' and 'APPROVE'
My DB Version in 10.2.0.3.0.
Hope I explain it properly. And if you have any other option without dense_rank still i will be happy.
Thanks in advance for your help.
AB
null
Message was edited by:
ABinstead of max(created_id) keep... use
smth like max(case when status_cd in ('APPROVE','REVIEW') then created_id end) keep... -
Does anyone know how or where to enter the ORDER BY clause when using a SQL data source in a load rule? I would prefer to do the ordering in the load rule rather than creating a view on the DB side to do this if at all possible.
According to the documentation "The SQL Statement box in the Open SQL Data Sources dialog box provides Select, From, and Where text boxes that help you write SQL queries. You can specify multiple data sources, filter the display of records, and specify how records displayed in Data Prep Editor are ordered and grouped." but I haven't found anywhere where you can order or group data. I don't need to be able group data I just want to be able to order my data to make the load process as efficient as possible.
I do sort the data when inserting it into the load table but Oracle doesn't necessarily insert the records into the table based on their order when going in.
We are currently on Essbase 11.1.1.3 and Oracle 11g.
Any help is greatly apprecied.Well DUH! Everyone knows that! :-)
Not sure why I never tried that, but it works. They need to update the documentation to say this, but we all know that will never happen.
Thanks again! -
Passing parameter in report for order by clause
how can we pass the name of the column on which we want the order by clause to sort as a parameter through parameter from in a report??
Hi Guptha,
We can create a bind parameter in report and we can send it as a parameter or enter in the parameter form.
The Query will be
select * from emp
order by :Order_Bu_Column
I think it will help you.
Regards,
Siva. -
Need Help With SQL GROUP BY and DISTINCT
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Hi,
user12036843 wrote:
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Sorry, it's unclear what you want.
Whenever you post a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using.
Do you want the output to contain one row for each row in the table, plus an extra row for each distinct order, showing something about the order as a whole (e.g., total inv_price or average extension_price)? If so, you need GROUP BY ROLLUP or GROUP BY GROUPING SETS .
If you want one row of output for each row of the table, but you want to include something that reflects the group as a whole (again, e.g, total inv_prive or average extension_pcie), then you can us analytic functions. (Most of the aggregate functions, such as SUM and AVG have analytic counterparts that can get the same results without collapsing the result set down to one row per group.)
Here's an example of how to use GROUP BY GROUPING SETS.
Way we're interested in employees' salary and commission from the scott.emp table:
SELECT deptno
, ename
, sal
, comm
FROM scott.emp
ORDER BY deptno
, ename
;Output:
` DEPTNO ENAME SAL COMM
10 CLARK 2450
10 KING 5000
10 MILLER 1300
20 ADAMS 1100
20 FORD 3000
20 JONES 2975
20 SCOTT 3000
20 SMITH 800
30 ALLEN 1600 300
30 BLAKE 2850
30 JAMES 950
30 MARTIN 1250 1400
30 TURNER 1500 0
30 WARD 1250 500Now say we want to add the total income (sal + comm, or just sal if there is no comm) to each row, and also to add a row for each department showing the total sal, comm and income in that department, like this:
` DEPTNO ENAME SAL COMM INCOME
10 CLARK 2450 2450
10 KING 5000 5000
10 MILLER 1300 1300
10 8750 8750
20 ADAMS 1100 1100
20 FORD 3000 3000
20 JONES 2975 2975
20 SCOTT 3000 3000
20 SMITH 800 800
20 10875 10875
30 ALLEN 1600 300 1900
30 BLAKE 2850 2850
30 JAMES 950 950
30 MARTIN 1250 1400 2650
30 TURNER 1500 0 1500
30 WARD 1250 500 1750
30 9400 2200 11600(This relies on the fact that ename is unique.) Getting those results is pretty easy, using GROUPING SETS:
SELECT deptno
, ename
, SUM (sal) AS sal
, SUM (comm) AS comm
, SUM ( sal
+ NVL (comm, 0)
) AS income
FROM scott.emp
GROUP BY GROUPING SETS ( (deptno)
, (deptno, ename)
ORDER BY deptno
, ename
;Notice that we're displaying SUM (sal) on each row. Most of the rows in the output are "groups" consisting of only one row from the table, so the SUM (sa) for that goup will be the sal for the one row in the group.
Edited by: Frank Kulash on Nov 23, 2011 2:03 PM
Added GROUPING SET example -
My activation date has passed but my order status ...
Phone line has been fitted a couple of days ago so should've been activated at any time up to midnight on the activation date. This has now passed but the order status is still in progress when I go to the track order page. The help page says that this means there's been a problem with my order.
Please help!!
Thanks
Solved!
Go to Solution.Once the Forum Mods have read your post they will post an invite here once you reply to them they will take personal ownership of the problem until resolved
do not send them a Personal Message as this is the incorrect contact method and cannot be properly tracked also the mod contacted may not be on shift for sometime and this will delay your help
If you want to say thanks for a helpful answer,please click on the Ratings star on the left-hand side If the reply answers your question then please mark as ’Mark as Accepted Solution’ -
Query hangs when given order by clause...help needed urgent
Hi ,
I have a table of size 4.1 GB.
QUERY IS :select * from rm_bil_bill order by bill_id desc;
the column Bill_id is primary key.
i have 6GB of temp tablespace.
the normal select works fine but then when it is suffixed with order by clause it is hanging for ever ...
Please help on this...
Thanks,
AshleeHI ,
Also like to add some information.
The table has been analysed on july 19th,
the explain plan for the above statement is :
SQL> SELECT * FROM TABLE( dbms_xplan.display );
PLAN_TABLE_OUTPUT
Plan hash value: 178181731
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)|
Time |
PLAN_TABLE_OUTPUT
| 0 | SELECT STATEMENT | | 24M| 3790M| | 1006K (2)|
03:21:17 |
| 1 | SORT ORDER BY | | 24M| 3790M| 10G| 1006K (2)|
03:21:17 |
| 2 | TABLE ACCESS FULL| RM_BIL_BILL | 24M| 3790M| | 123K (5)|
00:24:41 |
PLAN_TABLE_OUTPUT
9 rows selected.
SQL> SQL> SELECT * FROM TABLE(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 178181731
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)|
Time |
PLAN_TABLE_OUTPUT
| 0 | SELECT STATEMENT | | 24M| 3790M| | 1006K (2)|
03:21:17 |
| 1 | SORT ORDER BY | | 24M| 3790M| 10G| 1006K (2)|
03:21:17 |
| 2 | TABLE ACCESS FULL| RM_BIL_BILL | 24M| 3790M| | 123K (5)|
00:24:41 |
PLAN_TABLE_OUTPUT
9 rows selected.
THE TABLE DESCRIPTION:
SQL> desc rm_p01.RM_BIL_BILL
Name Null? Type
BILL_ID NOT NULL NUMBER(14)
STUDENT_ID NOT NULL NUMBER(14)
STUDENT_UIN NOT NULL VARCHAR2(20)
BILL_MONTH NOT NULL DATE
BILL_TYPE NOT NULL VARCHAR2(10)
SCHOOL_CODE NOT NULL VARCHAR2(10)
LEVEL_GRADE NOT NULL VARCHAR2(10)
CLASS_NAME VARCHAR2(10)
PUPIL_PROFILE_ID NOT NULL NUMBER(14)
BAL_BROUGHT_FORWARD NOT NULL NUMBER(10,2)
BILL_TOTAL_PAYMENT NOT NULL NUMBER(10,2)
BILL_OUTSTANDING_BAL NOT NULL NUMBER(10,2)
BILL_NET_CHARGES NOT NULL NUMBER(10,2)
BILL_TOTAL_PAYABLE NOT NULL NUMBER(10,2)
GENERATION_DATE NOT NULL DATE
GIRO_SO_IND CHAR(1)
GIRO_DEDUCTION_IND CHAR(1)
GIRO_DEDUCTION_DATE DATE
PRINT_DATA_EXTRACTION_IND CHAR(1)
PRINT_DATA_EXTRACTION_DATE DATE
REVIEW_IND CHAR(1)
REVIEW_DATE DATE
REVERSAL_MONTH DATE
VERSION_NO NOT NULL NUMBER(6)
CREATED_BY VARCHAR2(20)
CREATION_DATE DATE
LAST_UPDATED_BY VARCHAR2(20)
LAST_UPDATED_DATE DATE
BANK_ACCOUNT_NUMBER VARCHAR2(12)
BANK_ACRONYM VARCHAR2(30)
the table DDL :
CREATE TABLE "RM_P01"."RM_BIL_BILL"
( "BILL_ID" NUMBER(14,0) NOT NULL ENABLE,
"STUDENT_ID" NUMBER(14,0) NOT NULL ENABLE,
"STUDENT_UIN" VARCHAR2(20) NOT NULL ENABLE,
"BILL_MONTH" DATE NOT NULL ENABLE,
"BILL_TYPE" VARCHAR2(10) NOT NULL ENABLE,
"SCHOOL_CODE" VARCHAR2(10) NOT NULL ENABLE,
"LEVEL_GRADE" VARCHAR2(10) NOT NULL ENABLE,
"CLASS_NAME" VARCHAR2(10),
"PUPIL_PROFILE_ID" NUMBER(14,0) NOT NULL ENABLE,
"BAL_BROUGHT_FORWARD" NUMBER(10,2) NOT NULL ENABLE,
"BILL_TOTAL_PAYMENT" NUMBER(10,2) NOT NULL ENABLE,
"BILL_OUTSTANDING_BAL" NUMBER(10,2) NOT NULL ENABLE,
"BILL_NET_CHARGES" NUMBER(10,2) NOT NULL ENABLE,
"BILL_TOTAL_PAYABLE" NUMBER(10,2) NOT NULL ENABLE,
"GENERATION_DATE" DATE NOT NULL ENABLE,
"GIRO_SO_IND" CHAR(1),
"GIRO_DEDUCTION_IND" CHAR(1),
"GIRO_DEDUCTION_DATE" DATE,
"PRINT_DATA_EXTRACTION_IND" CHAR(1),
"PRINT_DATA_EXTRACTION_DATE" DATE,
"REVIEW_IND" CHAR(1),
"REVIEW_DATE" DATE,
"REVERSAL_MONTH" DATE,
"VERSION_NO" NUMBER(6,0) DEFAULT 0 NOT NULL ENABLE,
"CREATED_BY" VARCHAR2(20),
"CREATION_DATE" DATE DEFAULT SYSDATE,
"LAST_UPDATED_BY" VARCHAR2(20),
"LAST_UPDATED_DATE" DATE DEFAULT SYSDATE,
"BANK_ACCOUNT_NUMBER" VARCHAR2(12),
"BANK_ACRONYM" VARCHAR2(30),
PRIMARY KEY ("BILL_ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 NOLOGGING COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "DATAMEDIUM_RM_P" ENABLE
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS NOLOGGING
STORAGE(INITIAL 4294967296 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "DATAMEDIUM_RM_P"
Maybe you are looking for
-
Problem with scanning document in PDF format to computer
has anyone had a problem with scanning to the computer a document in pdf format from hp Photosmart 7525 e-All-in-One series wireless printer? The document appears in My Documents but when I try and open the document I get an error message that says
-
How do I find CD keys for software pre-installed on my computer?
Hi, All When I purchased my Tiger MAC, it came with so much software that I didn't get to opening and running all of them for a couple of YEARS! . I never has a problem burning DVD's until recently, so I never recieved any stimulation to try Toast. W
-
How to avoid a function module runnning parallely twice
Hello, There is a scenario, where user calls a function module via RFC. The requirement is to avoid the user from running the function module parallely twice or more because it may lead to dead lock problems. To realize this creati
-
Inserting 3D-PDF into a standard PDF
I have done this before many moons ago, see here: http://3d.onlinestoragesolution.com/PDF_MakePart_2D-Dwg/FS-11-008_2D.pdf but can't do it again. What I remember doing is create a u3d from an STP file, then: 1- open up the flat 2D PDF, go to a blank
-
Experience with DDR2 RAM from Legacy Electronics ?? (PM G5 Quad)
hi, I´m looking into upgrading my PowerMac G5 Quad with 8GB RAM DDR2(4x2GB), and came across a kit from Legacy Electronics for $740 (w/lifetime warranty). I already have 8GB from OWC installed, but they want $1100 for another 8GB.. Anyone had any exp