Using SELECT MAX(Substr( in a subquery to return specific rows
Oracle v10
Here's an example of a query and the output
SELECT ID, SAMPLEID, COMPOUNDNAME, REQUISITION, SUBSTR(REQUISITION,2,4) FROM SEARCH PL1 WHERE SAMPLEID = 'IA 0005 0166';
86907 IA 0005 0166 IA 0005 R2004:001160 2004
98158 IA 0005 0166 IA 0005 R2005:000956 2005I am attempting to only return the newest row of data, in this case the 2005 row.
I tried
SELECT ID, SAMPLEID, COMPOUNDNAME, REQUISITION, SUBSTR(REQUISITION,2,4) FROM SEARCH PL1
WHERE SAMPLEID = 'IA 0005 0166' AND
REQUISITION IN
(SELECT MAX(SUBSTR(REQUISITION,2,4)) FROM SEARCH PL2
WHERE SUBSTR(PL2.REQUISITION,2,4) = SUBSTR(PL1.REQUISITION,2,4));But it returns no results. I feel I am missing something simple.
TIA
Hi,
You're comparing a string to a 4-byte substring from the middle of itself. Those two will never be the same.
Also, I don't think you want the sub-query to be corellated.
Try this:
SELECT id
, sampleid
, compoundname
, requisition
, SUBSTR (requisition, 2, 4)
FROM search pl1
WHERE sampleid = 'IA 0005 0166'
AND SUBSTR (requisition, 2, 4) -- Changed
IN (
SELECT MAX (SUBSTR (requisition, 2, 4))
FROM search pl2
-- WHERE SUBSTR (pl2.requisition, 2, 4) = SUBSTR (pl1.requisition, 2, 4) -- Lose this, maybe
;If different substrings of requisition mean different things, then perhaps they should be stored in different columns. It will be easier to combine the different columns when you want to (e.g., for display) than it will be to split the single string apart every time you need to use only part of it, and it will be much more efficient as well.
If you need to combine them often, you could create a view, or, starting in Oracle 11, use a virtual column.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Edited by: Frank Kulash on Dec 20, 2010 12:59 PM
Formatted code
Similar Messages
-
Using SELECT MAX to default to certain days
Gurus,
Right now, I use SELECT MAX("File Date"."Date")FROM "Subject Area" to pull the most recent date available. I'd like for this to pull the last two or three days of data available. Any suggestions?
I have this set under a report filter for the analysis. Thanks in advance!Try this
SELECT File Date.Date saw_0, TOPN(File Date.Date, 3) saw_1, Facts."#Sales" saw_2 FROM "Subject Area" ORDER BY saw_0
Let me know updates
Edited by: Srini VEERAVALLI on May 6, 2013 5:10 PM
Your initial post talks about logical query from OBIEE, so I've logical query. try to put that in answers instead of running in Toad or sql developer etc..
Edited by: Srini VEERAVALLI on May 6, 2013 8:20 PM -
How to use select max and min query..
hi gurus,
we have got a custom report for develoment.
the report has to fetch the max and min salarys department wise....
how to pick up max & min sal ansal from table pa0008.Hi,
Try the following
select max(sal)
min(sal)
from <database table>
into <internal table>
group by department
where <where condition>.
Here we assume that sal is the field holding the salary and department is the name of the field in the database table. Where condition is optional.
Hope this helps.
Regards,
Sachin -
Subquery not returning NULL rows
Hi,
I have been working with SQL since very long, but sorry, I have not come across following problem.
In the FROM clause, I use one sub query and a table. If I run sub query alone, it lists records even if rows with RATE=NULL.
But when I join sub query with other table, it is not fetching any records for RATE=NULL.
SELECT *
FROM
(SELECT key, perceivedseverity, eventtime, nvl(rate,'NA') rate FROM tr_alarm_history a
WHERE eventtime = (SELECT MAX(eventtime) FROM tr_alarm_history WHERE key = a.key)) a,
tr_lot_list b
WHERE a.key = b.localtargetname
and b.ttid='IM_20110516_8711' ;
The sub query -
" SELECT key, perceivedseverity, eventtime, nvl(rate,'NA') rate FROM tr_alarm_history a
WHERE eventtime = (SELECT MAX(eventtime) FROM tr_alarm_history WHERE key = a.key) "
returns all records including RATE=NULLs. But when I join them, RATE columns with NULL will be filtered. Please note that joining condition (WHERE a.key = b.localtargetname) is not a problem as they will always match irrespective of RATE having NULL.
Please let me know why this behaviour and is there any other alternative where in I can get the records even if RATE column is NULL.
Thanks a lot for your help.
-AnandI am extreemly sorry. 2 or 3 examples I took were wrong one's, which were not having RATE=NULL. So I got into such confusion.
PLEASE INORE MY QUESTION.
And thanks for your valuable time.
With Best Wishes,
-Anand -
Materialized View hangs with SELECT MAX
Hi there,
I'm using Oracle 10.2.0.4 on a 64bit AIX system and I am having issues with creating a materialized view.
We have a large (1Tb) database and the large table the materialized view looks at is 200m rows.
I've created 5 other materialized views each with a select max clause and all looking at the same table.
When I created my problem MV I forget the select max and it created in 22mins.
I corrected my error by putting in the select max clause (so as to retrieve the top record) and the create MV ran for 16hrs+, I killed it.
If I just run the select statement at a sqlplus prompt it runs through in 22mins, if I create another object e.g. a table from the query it creates in 22mins.
So the question would be, why can I not create a MV using SELECT MAX on 10.2.0.4?
If I've missed any details don't hesitate to ask.
Thanks in advance.Hi Justin,
Thank you for your reply.
It has been upgraded to 9.2.0.8.0 from 9.1.... I'm not aware about the procedure used.
I could see a job scheduled for the materialized view , but that fails and it's broken after 16 attempts.
How to log the error generated by the Refresh Job?
Recreating the View - After the upgrade I have created the Materialized view again. Object T1 exists in the user schema User1.
I'm not explicitly getting any error but the refresh doesn't happens , so I couldn't find any records in the materialized view.
Thanks
GM -
Using select query in Subprogram block
Hello
Generally confusion arises at my work place on topic that whether to use cursor or anonymous block for the SELECT statement which mostly is going to return single row. In below example we can see the following statement may be returning a single:
"SELECT ename INTO v_ename FROM emp WHERE ID = P_ID; "
What approach you will use and why?
I always prefer to use Cursor in any case.
Thanks in advance,In this simple case, the simplest solution, and where you have most control as a programmer is to use an explicit cursor (yes, there would be those who argue that in recent versions of Oracle your performance would be best with an implicit cursor, but in practice this will probably make no difference). Here is how I would write:
FUNCTION Get_Ename(p_Id emp.ID%TYPE) return emp.ename%TYPE IS
CURSOR C1 IS
SELECT ename
FROM emp
WHERE ID = P_ID;
v_Ret_Val emp.ename%TYPE;
BEGIN
OPEN C1;
FETCH C1 INTO v_Ret_Val;
CLOSE C1;
RETURN v_Ret_Val;
END;Notice, no exception handling needed, not even if there is going to be no matches and even if there are multiple rows for the ID (which I doubt you would have if the ID is the primary key).
Packaging as a function, gives you something you can reuse and modify if needed later, without modifying all places where you perform this select.
Hope this helps,
Thomas -
Adding the results of subqueries, where one subquery returns no rows
I am creating a complex SQL statement- many of the columns consist of the sum of two subqueries. Here is a simplified example:
SELECT NAME, ID,
(SELECT AMT1 FROM TABLE1 WHERE ID = 111) + (SELECT AMT2 FROM TABLE2 WHERE ID = 222),
(SELECT AMT3 FROM TABLE3 WHERE ID = 333) + (SELECT AMT4 FROM TABLE4 WHERE ID = 444),
FROM TABLE
WHERE...
The problem is, within one select item, if one subquery returns no rows and the other returns a row of data, the sum of the two is displayed as zero. For example, if 'SELECT AMT1 FROM TABLE1 WHERE ID = 111' returns a row, with a value of AMT1 = 1000, and 'SELECT AMT2 FROM TABLE2 WHERE ID = 222' returns no rows, the result is displayed as 0, not 1000. It reminds me of when you add a number and a NULL, and get NULL - the number gets ignored.
Is there a way to embed some conditional logic in the subquery, to say 'if no rows returned, AMT = 0, else AMT = value'? Any help would be appreciated.Yikes, you appear to have stumbled upon DMFH!
You can use NVL like this -
SQL> select
2 (select 1 from dual) + (select 2 from dual) x
3 from dual;
X
3
SQL> edi
Wrote file afiedt.sql
1 select
2 (select 1 from dual) + (select 2 from dual where 0 = 1) x
3* from dual
SQL> /
X
SQL> edi
Wrote file afiedt.sql
1 select
2 (select 1 from dual) + nvl((select 2 from dual where 0 = 1),0) x
3* from dual
SQL> /
X
1
SQL>(DMFH = Data Model From Hell) -
Post Author: Aron Sereny
CA Forum: Data Connectivity and SQL
i want to limit the result set of the select to only the latest invoice for a given client.
so, I was hoping to use use
invoice.num = (select max( invoice.num).....
in the record selection...but it does not like my sub select in the where clause...any work around for this?
in other words...my select returns
1002 1
1002 2
1002 3
1001 1
998 1
998 2
but i only want the first 3 records (invNum= 1002, the max invNum for this client)
using CR XI, thanks for any insightPost Author: Aron Sereny
CA Forum: Data Connectivity and SQL
i am working with MS sql 2000
my rpt returns
102 1
102 2
101 1
i would like to limit the result set to the 102 id (the largest, most recent ID)
in query analyzer my select works fine with the where clause something like:
where....
and id = (select max (id) from.....)
crystal does not like the sub select in the where clause (select criteria)
thanks for any help -
How to select the max rowid from a subquery with group by
Hi Gurus,
Kindly help how to fix the following query because I'm getting Oracle error:ORA-01446.
select * from edy_raw_data a
where rowid in ( select max(rowid) from(
select email,max(date_updated) from edy_raw_data b
where b.email=a.email
group by email ))
The query select the max rowid from a sub query with group by.
Thanks in Advance.
BenjieWhy do you need to compare with rowid?
Wouldn't this suffice?
select * from edy_raw_data a
where (email,date_updated) = (select email, max(date_updated) from edy_raw_data b
where b.email=a.email
group by b.email ))* Note: untested -
Using Select statement in IF condition?
hi all,
Can i use select statement in IF COndition in pl sql ?
eg like- if( select 1 from ASD) then
end if;There is no way to do any kind of select statement inside if conditions.
Why don't test simple cases like this first?
An example to show it.
SQL> begin
2 if exists (select 1 from dual) then
3 dbms_output.put_line('ok');
4 end if;
5 end;
6 /
if exists (select 1 from dual) then
ERRORE alla riga 2:
ORA-06550: line 2, column 5:
PLS-00204: function or pseudo-column 'EXISTS' may be used inside a SQL
statement only
ORA-06550: line 2, column 2:
PL/SQL: Statement ignored
SQL> begin
2 if ( (select count(*) from dual) > 0 ) then
3 dbms_output.put_line('ok');
4 end if;
5 end;
6 /
if ( (select count(*) from dual) > 0 ) then
ERRORE alla riga 2:
ORA-06550: line 2, column 8:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
( - + case mod new not null others <an identifier>
<a double-quoted delimited-identifier> <a bind variable> avg
count current exists max min prior sql stddev sum variance
execute forall merge time timestamp interval date
<a string literal with character set specification>
<a number> <a single-quoted SQL string> pipe
<an alternatively-quoted string literal with character set specification>
<an alternativ
ORA-06550: line 2, column 33:
PLS-00103: Encountered the symbol ")" when expecting one of the following:
. , @ ; for <an identifier>
<a double-quoted delimited-identifier> group having intersect
minus order partition start subpartition union where connect
SQL> begin
2 if ( 0 in (select count(*) from dual) ) then
3 dbms_output.put_line('ok');
4 end if;
5 end;
6 /
if ( 0 in (select count(*) from dual) ) then
ERRORE alla riga 2:
ORA-06550: line 2, column 12:
PLS-00405: subquery not allowed in this context
ORA-06550: line 2, column 2:
PL/SQL: Statement ignoredBye Alessandro -
Select Max and ResultSet Problem With Access
The following code is producing a 'null pointer excepetion' error and I know why it is occurring I just do not know how to fix the problem.
Basically I want to automitically generate a unique ID that is one number higher than the max ID (data is stored within an Access database). The ID field is made up of first and last initial taken from parsing previous login info ('JS-01', 'JS-02', ect.). If there are no IDs in the database that match your login info I want to set the new ID equal to 'JS-01' if your login is 'James Smith' for example.
The problem is explained within the code below.
<%
//define resultset and statement
ResultSet rss=null;
ResultSet rs=null;
Statement stmt=null;
//HERE IS WHERE YOU PARSE THE LOGIN INFO
String finitial = (String)session.getAttribute("vfirst");//vfirst=JIM
String linitial = (String)session.getAttribute("vlast");//vlast=SMITH
char f = finitial.charAt(0);
char n = linitial.charAt(0);
String sID = f+""+n;//NOW sID CONTAINS 'JS'
try {
//Using the current database connection create a statement
stmt=con.createStatement();
//QUERY TO SELECT MAX ID
//NOTE: CURRENTLY THERE ARE NO IDs LIKE 'JS' IN THE DATABASE !!!!!!
String sql="SELECT Max(ID) As MaxID FROM tblError Where ID LIKE '%"+sID+"%'" ;
rs = stmt.executeQuery(sql);
String newID;
//HERE THE RESULT SET SHOULD BE NULL BUT IT IS NOT. I KNOW THIS BECAUSE WHEN I REPLACE String iID WITH A LITERAL LIKE 'JS-03' THE LOGIC WILL EXECUTE CORRECTLY AND GIVE ME 'JS-04'. IF I LEAVE THE CODE LIKE IT IS THEN I GET THE NULL POINTER VALUE ERROR BECAUSE YOU CANNOT RESOLVE "MaxID" WHEN THE RESULT SET IS NULL. IF THE RESULT SET IS NULL IT SHOULD NOT EVEN EXECUTE ANY OF THIS CODE WITHIN THE 'if' STATEMENT, BUT IT IS. SO BASICALLY JSP IS LEAVING ME WITH A MAJOR OXYMORON AND I WOULD APPRECIATE ANY ADVICE THAT WOULD HELP ME SOLVE THIS PROBLEM.
if(rs.next()){
String iID = rs.getString("MaxID");
String letters = iID.substring(0,3);
int numbers = Integer.parseInt(iID.substring(3,5));
numbers = numbers + 1;
if(numbers < 10){
newID = letters + "0" + numbers;}
else{
newID = letters + numbers;
else{//IF THERE IS NO RESULT SET THAN THE ID SHOULD BE 'JS-01'
newID = sID + "-01";
%>
Because this an Access database I cannot use any null exception functions such as NVL or COALESCE which are specific to Oracle and SQL Server I beleive.The max() will return a result set, even if the max value is null.
You should check to see if iID is null.
if(rs.next())
String iID = rs.getString("MaxID");
if (iID == null)
newID = sID + "-01";
else
String letters = iID.substring(0,3);
... etc ...
} -
How to select max (field) and one more field from table?
Hi experts!
I need to select maximum value of ENDDA from PA0023 and BRANC of max ENDDA.
How can I do that ?
When I trying this code:
This is the code:
SELECT MAX( endda ) branc
FROM pa0023
INTO (pa0023-endda, pa0023-branc).
I get error message:
The field "PA0023~BRANC" from the SELECT list is missing
in the GROUP BY clause. Addition INTO wa or INTO (g1,...,gn) is required.
So what is the problem?
Thanks forehead.Hi
Though am not totally sure of your requirement, check below code samples without any syntax errors:
1. As per you current coding:
TABLES: pa0023.
SELECT MAX( endda ) branc
FROM pa0023
INTO (pa0023-endda, pa0023-branc)
GROUP BY branc.
ENDSELECT.
2. Above code results only on one record where as the criteria can be more than one. Eg: for a specific data more than one record can exist. Below code helps you handle the same:
TABLES: pa0023.
TYPES: BEGIN OF t_pa0023,
endda TYPE endda,
branc TYPE brsch,
END OF t_pa0023.
DATA: i_pa0023 TYPE TABLE OF t_pa0023,
wa_pa0023 TYPE t_pa0023.
SELECT MAX( endda ) branc
FROM pa0023
INTO TABLE i_pa0023
GROUP BY branc.
LOOP AT i_pa0023 INTO wa_pa0023.
ENDLOOP.
3. If the requirement is to get the Industry Key for the record with highest End Date. We can acheive it by using subquery something like:
TABLES: pa0023.
SELECT SINGLE endda branc
FROM pa0023
INTO (pa0023-endda, pa0023-branc)
WHERE endda = ( SELECT MAX( endda ) FROM pa0023 ).
Kind Regards
Eswar -
How to use Function MAX in xsl
Hi ,
iam facing a unique issue
i want to print maximum postion by using the function MAX
My style sheet is working fine in Jdev but same XSL sheet is giving error when i run it in oracle Applications.
below is xsl logic
<xsl:template name="ttpgds" match="ARXEURSL" mode="temp2">
<xsl:variable name="x">
<xsl:for-each-group select="G_ROW[INTRA_EU_TRX_CODE =('GOOD')]" group-by="concat(VAT_TAX_NO,BILL_CUST_NAME,INTRA_EU_TRX_CODE)">
<CHKPST><xsl:value-of select="position()"/></CHKPST><xsl:text>
</xsl:text>
</xsl:for-each-group>
</xsl:variable>
<xsl:for-each select="$x">
<xsl:variable name="jCount" select="max(CHKPST)"/>
<xsl:value-of select="ceiling($jCount)"/>
</xsl:for-each>
</xsl:template>in oracle applications iam getting below error:
Caused by: oracle.xdo.parser.v2.XPathException: Expected ')' instead of 'CHKPST'.
may i know how i can use the function MAX in XSl ??
Any suggestions?
Thanks
AnilHi,
Hope the following helps..
1)
LOOP AT IT_OUTPUT.
Call the function module to get the tracking number and store the output in the
variable V_TRACKINGNO.
IT_OUTPUT-TRACKING_NO = V_TRACKINGNO.
MODIFY IT_OUTPUT TRANSPORTING TRACKING_NO.
ENDLOOP.
2) Date conversion
DATA: V_CHAR(10) VALUE '2006.11.17'.
DATA: V_DATE TYPE SYDATUM.
CONCATENATE V_CHAR(4) V_CHAR5(2) V_CHAR8(2) INTO V_DATE.
WRITE: V_DATE TO V_CHAR MM/DD/YYYY.
WRITE: / 'MM/DD/YYY Format - ', V_CHAR.
Please make sure to reward points for helpful answers..
Thanks,
Naren -
Problem with Select MAX( field ) in OO
Hi all,
I have this statement:
SELECT SINGLE RUECK MAX( RMZHL ) BUDAT STZHL
INTO K_CONFIRM
FROM AFRU
WHERE AUFNR EQ P_ORDER
AND VORNR EQ P_OPER
GROUP BY RUECK RMZHL BUDAT STZHL.
My requirement is I need to use a work area (not an internal table) and ENDSELECT is not allowed. The result is not selecting the Maximum RMZHL, it will always return the first record.
How can I correctly do this in OO? Thanks in advanc.eIf you use GROUP BY in your query then the set functions (MAX,SUM, Count) not possible...
refer:
http://help.sap.com/saphelp_nw70/helpdata/en/be/c7fe3f70cac342e10000000a1550b0/frameset.htm -
Oracle error while using function dbms_lob.substr()
Following sql statement is causing error select dbms_lob.substr(clob_colum,32767) from Table* when the size of clob_column goes above 4 KB. The error message is given below
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 1
The issue is getting resolved when reducing the size of the CLOB column.
Is this a limitation of oracle query? Can anybody please help me to resolve this error? Thanks in Advance.
Regards,
ShineHi.
>
We are using this query inside a package and the data is used to generate an XML file and it finally used to generate a pdf report. There exists many clob records with huge size and in that case report execution fails with the oracle message.
>
While the XML file is generated or PDF report?
Which message? ORA-06502: PL/SQL: numeric or value error: character string buffer too small ???
>
So we need to modify the query in a way that it executes fine even if the size is more than 4 KB(upto a possible size). I tried using substr function against the clob column but it does not returned any value.
>
Then, do you need the first 4 KB or the entire CLOB?
Can't you write CLOB directly?
Please post some example data as well as your desired output in order to understand completely your problem and test our ideas.
Regards.
Maybe you are looking for
-
eggcave.com is being blocked for my use due to badware-I trust this site and have clicked the appropriate button but the security is still blocking me.Turn this damn thing off NOW before my virtual eggs die as I ca't care for them-or tell me were and
-
Text file storing in a database table
I have a text file, that contains so many lines in it,.. Now the problem is that.. I want to store my text file with the pl/sql code in a database table.... plz suggest, how to create a table and how to store that text file in a database table.....
-
Photoshop CS6 keeps freezing when I work with large files
I've had problems with Photoshop CS6 freezing on me and giving me RAM and Scratch Disk alerts/warnings ever since I upgraded to Windows 8. This usually only happens when I work with large files, however once I work with a large file, I can't seem to
-
«Adobe Illustrator CC 2014 quit unexpectedly» last upgrade
What could be the path to solve this? Thanks.
-
MfE: "Maximum number of mailboxes defined" error
I have had to wipe/reset and reinstall my E72. I have recreated my POP and Hotmail messaging accounts OK using Nokia EMail (www.email.nokia.com), but when I try to create my company Exchange account I get the error message "Maximum number of mailboxe