Returning specific rows within a resultset.
I have a table with the following rows:
Category Site Title
======== ==== ======
1 1 sometitle
123 1 sometitle
128 1 sometitle
4 1 sometitle
10 1 sometitle
I have a REF cursor that looks like this:
OPEN RefCursor FOR
SELECT Category, Site, Title
FROM TableName
WHERE Site = 1
ORDER BY Category;
Now...Here is the catch. In that same select statement, I want to be able to retrieve a specific range of rows to return, once the 'order by' is done.
I want to be able to execute my query, having it return rows 2 to 4...
So my RefCursor should contain:
Category Site Title
======== ==== ======
4 1 sometitle
10 1 sometitle
123 1 sometitle
The two important things are this:
1- The initial resultset must be sorted first..THEN I want to select specific rows.
2- The final result set MUST be a Ref Cursor.
Anyone have suggestions?
This will retrieve ordered rows 2 -4.
(SELECT Category, Site, Title
FROM
(select category, site, title
from tablename
order by category)
WHERE Rownum < 5)
MINUS
(SELECT Category, Site, Title
FROM
(select category, site, title
from tablename
order by category)
WHERE Rownum < 2)
/
Similar Messages
-
How to colour specific rows within an WebDynpro ALV
Hi everyone,
I need to colour only specific rows of an ALV. I've already scoured sdn and implemented the solutions that I found but none of them seems to be working okay.
I have an ALV table and I want to highlight only a few rows based on a certain logic.
I've defined a context node that defines 2 attributes: textview_design and cell_design.
LOOP AT ft_out_purchase_order_temp INTO ls_out_purchase_order_temp.
if ....
ls_out_purchase_order_temp-textview_design = cl_wd_text_view=>e_design-standard.
ls_out_purchase_order_temp-cell_design = cl_wd_table_column=>e_cell_design-standard.
else.
ls_out_purchase_order_temp-cell_design = cl_wd_table_column=>e_cell_design-total.
ls_out_purchase_order_temp-textview_design = cl_wd_text_view=>e_design-emphasized.
endif.
ENDLOOP.
lr_column_settings ?= po_alv_config_table.
lr_column = lr_column_settings->get_column( 'EBELN' ).
lr_column = po_alv_config_table->if_salv_wd_column_settings~get_column( 'EBELN' ).
lr_column->set_cell_design_fieldname( value = 'CELL_DESIGN' ).
This code works but the thing is that the whole column named 'EBELN' is coloured light green. This is strange because I've instructed the system that the design of the column EBELN is controlled by the field CELL_DESIGN and this field has the following values:
10 (light green)
33 (light blue)
10
10
10
33
10
33
Any ideas?Hii,
To color a particular row you need to follow two things.
1. Specify condition based on which the row will be colored i.e. set the value for the attribute 'CELL_DESIGN'.
2. Get all column references and set the cell design field name with 'CELL_DESIGN'.
Get all column reference.
DATA : LT_COLUMNS TYPE SALV_WD_T_COLUMN_REF,
LS_COLUMNS TYPE SALV_WD_S_COLUMN_REF.
LT_COLUMNS = LR_COLUMN_SETTINGS->GET_COLUMNS( ).
configure column
LR_COLUMN_SETTINGS ?= LV_VALUE. " column functions
LT_COLUMNS = LR_COLUMN_SETTINGS->GET_COLUMNS( ).
set cell design for all.
In your case if a single column is getting colored the then the reason might be
1.every record satisfying your if condition specified.
2.you have set cell design in that particular field name.
Regards,
Monishankar C -
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.
TIAHi,
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 -
Query executed within a plug-in script returns 0 rows, although data exists
I created a plug-in script for algorithm entity: Service Quantity Rule.
The script calls a business service that I created using query zones. The query returns the values of the bill segment (ci.bseg.bseg_id and ci_bseg.closing_bseg_sw) that is created while running a bill manually. The zone receives the bseg_id as a parameter.
The problem is that when I execute the business service within the plug-in script the business services returns 0 rows even though the data is actually being stored in the database.
The script calculates some SQI values and saves it to the bill segment based on a response that is received from MDM (I'm using the usage request object).
Steps:
1.- Create Bill. The bill segment is created in error as it is waiting for the bill determinants to be sent from the MDM. If I test the zone with the bseg_id (as a parameter) of the newly created bill segment it works fine.
2.- We send a message from the MDM to CC&B. The message is received and processed and it gets to a point when the usage updates the bill segment.
3.- After the bill segment has been updated with the values from the usage request object it starts executing the plug-in script.
4.- I obtain the bseg_id from the usage request and use the business service (passing the bseg_id as a parameter) and it returns no result.
5.- The process finishes and if test the zone with the bseg_id (as a paramter) of the billing segment it works fine.
So apparently during the execution of the script after the billing determinants are received from MDM I can't have access to the Bill segment that was created, even if the physically the record exists in the database (CI_BSEG).
I also tried instantiating an object related with the bill segment and got the same result.
Any idea or clue of what is happening?Could you be more explicit.
What CC&B version?
What MDM version?
More details are required for:
2.- We send a message from the MDM to CC&B. The message is received and processed and it gets to a point when the usage updates the bill segment.
3.- After the bill segment has been updated with the values from the usage request object it starts executing the plug-in script.
4.- I obtain the bseg_id from the usage request and use the business service (passing the bseg_id as a parameter) and it returns no result. -
Bug Report: ResultSet.isLast() returns false when queries return zero rows
When calling the method isLast() on a resultset that contains zero (0) rows, false is returned. If a resultset contains no rows, isLast() should return true because returning false would indicate that there are more rows to be retrieved.
Try the following Java source:
import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.*;
public class Test2 {
public static void main (String [] args) throws Exception {
Connection conn = null;
String jdbcURL = "jdbc:oracle:thin:@" +
"(DESCRIPTION=(ADDRESS=(HOST=<host computer>)"+
"(PROTOCOL=tcp)(PORT=<DB port number>))"+
"(CONNECT_DATA=(SID=<Oracle DB instance>)))";
String userId = "userid";
String password = "password";
try{
// Load the Oracle JDBC Driver and register it.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// *** The following statement creates a database connection object
// using the DriverManager.getConnection method. The first parameter is
// the database URL which is constructed based on the connection parameters
// specified in ConnectionParams.java.
// The URL syntax is as follows:
// "jdbc:oracle:<driver>:@<db connection string>"
// <driver>, can be 'thin' or 'oci8'
// <db connect string>, is a Net8 name-value, denoting the TNSNAMES entry
conn = DriverManager.getConnection(jdbcURL, userId, password);
} catch(SQLException ex){ //Trap SQL errors
// catch error
//conn = new OracleDriver().defaultConnection(); // Connect to Oracle 8i (8.1.7), use Oracle thin client.
PreparedStatement ps = conn.prepareStatement("select 'a' from dual where ? = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Use any query that will return zero rows.
ps.setInt(1, 1); // Set the params so that the query returns 0 rows.
ps.setInt(2, 2);
ResultSet rs = ps.executeQuery();
System.out.println("1. Last here? " + rs.isLast());
while (rs.next()) {
// do whatever
System.out.println("2. Last here? " + rs.isLast());
ps.close();
rs.close();
EXPECTED RESULT -
1. Last here? true
2. Last here? true
ACTUAL RESULT -
1. Last here? false
2. Last here? false
This happens to me on Oracle 9.2.0.1.0.387561,
For your information, I discovered this problem from
running a query that did access an actual DB table.
Try it and let me know.I did say I was only guessing, and yes, I did try it (after I posted my reply, and before I read yours). And I did check the query plan for the queries I tried -- to verify that they were actually doing some database "gets".
In any case, the usual way that I determine whether a "ResultSet" is empty is when the very first invocation of method "next()" returns 'false'. Is that not sufficient for you?
Good Luck,
Avi. -
Returning a subset of rows through a ResultSet WITHOUT rownum?
I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
1. Get SQL from TOPLink
2. Pass SQL through a Statement
3. Get resulting ResultSet
At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
Thanks,
Michael Allen
[email protected]Hi Michael,
Is there some sort of selection criteria in which you could use return the required 200-250 rows of data? If so, I would embed that into the TopLink query.
Another option is using the ORDER BY operator. Without order, constructing a query of elements 200-250 twice would not guarentee that they would be the same elements.
You can also construct your own SQL statement and execute it directly on a TopLink session.
Darren Melanson
Strategic Implementation Consultant
Oracle Canada.
I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
1. Get SQL from TOPLink
2. Pass SQL through a Statement
3. Get resulting ResultSet
At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
Thanks,
Michael Allen
[email protected] -
How do you return the number of Rows in a ResultSet??
How do you return the number of Rows in a ResultSet? It's easy enough to do in the SQL query using COUNT(*) but surely JDBC provides a method to return the number of rows.
The ResultSetMetaData interface provides a method for counting the number of columns but nothing for the rows.
ThanksNo good way before JDBC2.0. u can use JDBC2.0 CachedRowSet.size() to retrieve the number of rows got by a ResultSet.
-
Return the rows of the table where a column contains a specific value first
I want my query to return the rows of the table where a column contains a specific values first in a certain order, and then return the rest of the rows alphabetized.
For Example:
Country
ALBANIA
ARGENTINA
AUSTRALIA
CANADA
USA
Now i want USA and CANADA on top in that order and then other in alphabetized order.
Edited by: 986155 on Feb 4, 2013 11:12 PM986155 wrote:
If it is 2 then i can write a case... i want generalised one where may be around 5 or 6 mentioned should be in descending order at the top and remaining in ascending order there after.Computers tend not to work in 'generalized' ways... they require specifics.
If you store your "top" countries in a table you can then simply do something like...
SQL> ed
Wrote file afiedt.buf
1 with c as (select 'USA' country from dual union
2 select 'Germany' from dual union
3 select 'India' from dual union
4 select 'Australia' from dual union
5 select 'Japan' from dual union
6 select 'Canada' from dual union
7 select 'United Kingdom' from dual union
8 select 'France' from dual union
9 select 'Spain' from dual union
10 select 'Italy' from dual
11 )
12 ,t as (-- top countries
13 select 'USA' country from dual union
14 select 'United Kingdom' from dual union
15 select 'Canada' from dual
16 )
17 select c.country
18 from c left outer join t on (t.country = c.country)
19* ORDER BY t.country, c.country
SQL> /
COUNTRY
Canada
USA
United Kingdom
Australia
France
Germany
India
Italy
Japan
Spain
10 rows selected. -
Return specific number of rows depending on the data in a column in table
Hi,
I have a table named orders which has column orderid and noofbookstoorder in addition to other columns.
I want to query the orders table and depending on the value of the 'noofbookstoorder' value return that number of rows.
Eg
Orderid noofbookstoorder
1 1
2 3
3 2
when I query the above data saying
select * from orders where orderid=2;
since it has noofbookstoorders value as 3 the query should return 3 rows and when I query
select * from orders where orderid=3;
it should return 2 rows and
select * from orders where orderid=1;
should return 1 row.
Is it possible to achieve this. If yes, then how do I write my query.
Thanks in advance.with t as (
select 1 Orderid,1 noofbookstoorder from dual union all
select 2,3 from dual union all
select 3,2 from dual
select t.*
from t,
table(cast(multiset(select 1 from dual connect by level <= noofbookstoorder) as sys.OdciNumberList))
where Orderid = <order-id>
/For example:
SQL> with t as (
2 select 1 Orderid,1 noofbookstoorder from dual union all
3 select 2,3 from dual union all
4 select 3,2 from dual
5 )
6 select t.*
7 from t,
8 table(cast(multiset(select 1 from dual connect by level <= noofbookstoorder) as sys.OdciNumberList))
9 where Orderid = 2
10 /
ORDERID NOOFBOOKSTOORDER
2 3
2 3
2 3
SQL> with t as (
2 select 1 Orderid,1 noofbookstoorder from dual union all
3 select 2,3 from dual union all
4 select 3,2 from dual
5 )
6 select t.*
7 from t,
8 table(cast(multiset(select 1 from dual connect by level <= noofbookstoorder) as sys.OdciNumberList))
9 where Orderid = 3
10 /
ORDERID NOOFBOOKSTOORDER
3 2
3 2
SQL> with t as (
2 select 1 Orderid,1 noofbookstoorder from dual union all
3 select 2,3 from dual union all
4 select 3,2 from dual
5 )
6 select t.*
7 from t,
8 table(cast(multiset(select 1 from dual connect by level <= noofbookstoorder) as sys.Odc
iNumberList))
9 where Orderid = 1
10 /
ORDERID NOOFBOOKSTOORDER
1 1
SQL> -- And if you want to select multiple orders
SQL> with t as (
2 select 1 Orderid,1 noofbookstoorder from dual union all
3 select 2,3 from dual union all
4 select 3,2 from dual
5 )
6 select t.*
7 from t,
8 table(cast(multiset(select 1 from dual connect by level <= noofbookstoorder) as sys.Odc
iNumberList))
9 where Orderid in (2,3)
10 /
ORDERID NOOFBOOKSTOORDER
2 3
2 3
2 3
3 2
3 2
SQL> SY.
Edited by: Solomon Yakobson on Oct 26, 2009 7:36 AM -
Problem with database control returning multiple rows as Array using Oracle
Has anybody using Oracle gotten a Database control that
returns multiple rows to work returning an array?
The only way I can seem to return multiple rows is by returning
a RowSet. Returning an array gives me a NullPointerException
(when called within a pageFlow). When calling a database control
that returns an array from a web service I get a
"java.sql.SQLException: ResultSet has no more data." error.
The samples using the pointbase database seem to work, but when I
converted the CustomerDBClient web service to use Oracle, it starts
failing on calling the database control that returns an array
with: "java.sql.SQLException: ResultSet has no more data."
Has anybody gotten this to work using Oracle?
I'm also having some problem returning an Iterator. It seems
to work when called from a web service, but returns nothing
if called from a page flow.
I'm using Oracle 8.1.7 and WebLogic 8.1.
EricDo you need a particular service pack installed to return an array of custom object?
I am getting a ResultSet contained no data error when trying.
Thanks,
-Thomas
"Robin Karlin" <[email protected]> wrote:
>
Eddie O'Neil <[email protected]> wrote:
All--
Unfortunately, returning an Iterator to a JPF (or JSP) from a
database control is broken in WLW 8.1, though it will work inside of
a
JWS or JCS.
There shouldn't be a problem with returning an array of objects out
of Oracle to the JPF, and if you need an Iterator specifically, youcan
wrap the array in an Iterator implementation.
Sorry for the inconvenience.
Eddie
Lenny wrote:
I have gotten it to work on Oracle using Array:)
However, I haven't gotten it to work on Oracle using Iterator:( Itis so
simple, but doesn't work:(
"Eric Dokken" <[email protected]> wrote in message
news:[email protected]...
Has anybody using Oracle gotten a Database control that
returns multiple rows to work returning an array?
The only way I can seem to return multiple rows is by returning
a RowSet. Returning an array gives me a NullPointerException
(when called within a pageFlow). When calling a database control
that returns an array from a web service I get a
"java.sql.SQLException: ResultSet has no more data." error.
The samples using the pointbase database seem to work, but when I
converted the CustomerDBClient web service to use Oracle, it starts
failing on calling the database control that returns an array
with: "java.sql.SQLException: ResultSet has no more data."
Has anybody gotten this to work using Oracle?
I'm also having some problem returning an Iterator. It seems
to work when called from a web service, but returns nothing
if called from a page flow.
I'm using Oracle 8.1.7 and WebLogic 8.1.
Eric
I get the same error that Eric reported when trying to return an Array
of objects.
It is really frustrating because I can't use much of the built-in control
logic
that WLW provides. All I did was create a data pool for Oracle and a
datasource.
I modified the sample app in C:\bea81\weblogic81\samples\workshop\SamplesApp\WebApp\callJavaControl
to point to that datasource and I get the error that Eric reports above.
Can
anyone help me out????
Thanks,
Robin -
Custom row-fetch and how to get column values from specific row of report
Hi -- I have a case where a table's primary key has more than 3 columns. My report on the
table has links that send the user to a single-row DML form, but of course the automatic
fetch won't work because 1) I can't set more than 3 item values in the link and 2) the
auto fetch only handles 2 PK columns.
1)
I have written a custom fetch (not sure it's the most elegant, see second question) that is working
for 3 or few PK columns (it references the 1-3 item values set in the link), but when there are
more than 3, I don't know how to get the remaining PK column values for the specific row that was
selected in the report. How can I access that row's report column values? I'll be doing it from the
form page, not the report page. (I think... unless you have another suggestion.)
2)
My custom fetch... I just worked something out on my own, having no idea how this is typically
done. For each dependent item (database column) in the form, I have a source of PL/SQL
function that queries the table for the column in question, using the primary key values. It works
beautifully, though is just a touch slow on my prototype table, which has 21 columns. Is there
a way to manually construct the fetch statement once for the whole form, and have APEX be smart
about what items get what
return values, so that I don't have to write PL/SQL for every item? Because my query data sources
are sometimes in remote databases, I have to write manual fetch and dml anyway. Just would like
to streamline the process.
Thanks,
CarolHI Andy -- Well, I'd love it if this worked, but I'm unsure how to implement it.
It seems I can't put this process in the results page (the page w/ the link, that has multiple report rows), because the link for the row will completely bypass any after-submit processes, won't it? I've tried this in other conditions; I thought the link went directly to the linked-to page.
And, from the test of your suggestion that I've tried, it's not working in the form that allows a single row edit. I tried putting this manually-created fetch into a before header process, and it seems to do nothing (even with a hard-coded PK value, just to test it out). In addition, I'm not sure how, from this page, the process could identify the correct PK values from the report page, unless it can know something about the row that was selected by clicking on the link. It could work if all the PK columns in my edit form could be set by the report link, but sometimes I have up to 5 pk columns.
Maybe part of the problem is something to do with the source type I have for each of the form items. With my first manual fetch process, they were all pl/sql functions. Not sure what would be appropriate if I can somehow do this with a single (page level?) process.
Maybe I'm making this too hard?
Thanks,
Carol -
To color a specific row in a Table UI element
Hello Experts,
We have a requirement to highlight (with distinguish color) a specific row of a table UI based on column data.
Suppose we have a table with 5 column and 10 row, now if the data on 5th column greater than some XYZ value then we need to highlight the specific row with a different color.
Can anyone please help me to achieve this requirement?
Thanks & Regards,
Sambaran ChakrabortyHi,
In your outline, I am missing quite a few prerequisites which I mentioned (not sure if you have implemented them already)
your sub node, does it have singleton=false, cardinality 1..1 and selection cardinality 1..1?
The attribute of type TableCellDesign in that sub node, does it have the calculated property to true?
If you've bound each table column's cellDesign property to this calculated attribute, you just put some code in the generated generated get<SubNode><CalcAttribute> method to set the color
For instance by just entering the line
return WDTableCellDesign.CRITICALVALUE_LIGHT
in that method will render each linked cell to that color
Not sure what else I can say to explain this, there's not much to code... -
How just return one row of a one to many join..
So I have a one to many join where the SMOPERATOR table has data I need however it has a couple of rows that match the JOIN condition in there. I just need to return one row. I think this can be accomplished with a subquery in the join however have not been able to come up with the right syntax to do so.
So:
SELECT "NUMBER" as danumber,
NAME,
SMINCREQ.ASSIGNMENT,
SMOPERATOR.PRIMARY_ASSIGNMENT_GROUP,
SMOPERATOR.WDMANAGERNAME,
SMINCREQ.owner_manager_name,
SMINCREQ.subcategory, TO_DATE('01-'||TO_CHAR(open_time,'MM-YYYY'),'DD-MM-YYYY')MONTHSORT,
(CASE WHEN bc_request='f' THEN 'IAIO'
WHEN (bc_request='t' and substr(assignment,1,3)<>'MTS') THEN 'RARO'
WHEN (bc_request='t' and substr(assignment,1,3)='MTS') THEN 'M'
ELSE 'U' end) as type
from SMINCREQ
left outer join SMOPERATOR on SMINCREQ.assignment=SMOPERATOR.primary_assignment_group
WHERE SMINCREQ.owner_manager_name=:P170_SELECTION and SMOPERATOR.wdmanagername=:P170_SELECTION
AND open_time BETWEEN to_date(:P170_SDATEB,'DD-MON-YYYY') AND to_date(:P170_EDATEB,'DD-MON-YYYY')
AND
(bc_request='f' and subcategory='ACTIVATION' and related_record<>'t')
OR
(bc_request='f' and subcategory<>'ACTIVATION')
OR
(bc_request='t' and substr(assignment,1,3)<>'MTS')
order by OPEN_TIMeHi,
This sounds like a Top-N Query , where you pick N items (N=1 in this case) off the top of an orderded list. I think you want a separate ordered list for each assignment; the analytic ROW_NUMBER function does that easily.
Since you didn't post CREATE TABLE and INSERT statements for your sample data, I'll use tables from the scott schema to show how this is done.
Say you have a query like this:
SELECT d.dname
, e.empno, e.ename, e.job, e.sal
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
ORDER BY dname
;which produces this output:
DNAME EMPNO ENAME JOB SAL
ACCOUNTING 7934 MILLER CLERK 1300
ACCOUNTING 7839 KING PRESIDENT 5000
ACCOUNTING 7782 CLARK MANAGER 2450
RESEARCH 7876 ADAMS CLERK 1100
RESEARCH 7902 FORD ANALYST 3000
RESEARCH 7566 JONES MANAGER 2975
RESEARCH 7369 SMITH CLERK 800
RESEARCH 7788 SCOTT ANALYST 3000
SALES 7521 WARD SALESMAN 1250
SALES 7844 TURNER SALESMAN 1500
SALES 7499 ALLEN SALESMAN 1600
SALES 7900 JAMES CLERK 950
SALES 7698 BLAKE MANAGER 2850
SALES 7654 MARTIN SALESMAN 1250Now say you want to change the query so that it only returns one row per department, like this:
DNAME EMPNO ENAME JOB SAL
ACCOUNTING 7782 CLARK MANAGER 2450
RESEARCH 7876 ADAMS CLERK 1100
SALES 7499 ALLEN SALESMAN 1600where the empno, ename, job and sal columns on each row of output are all taken from the same row of scott.emp, though it doesn't really matter which row that is.
One way to do it is to use the analytic ROW_NUMBER function to assign a sequence of unique numbers (1, 2, 3, ...) to all the rows in each department. Since each sequence startw with 1, and the numbers are unique within a department, there will be exactly one row per departement that was assigned the numebr 1, and we''ll display that row.
Here's how to code that:
WITH got_r_num AS
SELECT d.dname
, e.empno, e.ename, e.job, e.sal
, ROW_NUMBER () OVER ( PARTITION BY d.dname
ORDER BY e.ename
) AS r_num
FROM scott.dept d
JOIN scott.emp e ON d.deptno = e.deptno
SELECT dname
, empno, ename, job, sal
FROM got_r_num
WHERE r_num = 1
ORDER BY dname
;Notice that he sub-query got_r_num is almost the same as the original query; only it has one additional column, r_num, in the SELECT clause, and the sub-qeury does not have an ORDER BY clause. (Sub-queries almost never have an ORDER BY clause.)
The ROW_NUMBER function must have an ORDER BY clause. In this example, I used "ORDER BY ename", meaning that, within each department, the row with the first ename (in sort order) will get r_num=1. You can use any column, or expression, or expressions in the ORDER BY clause. You muight as well use something consistent and predictable, like ename, but if you really wanted arbitrary numbering you could use a constant in the analytic ORDER BY clause, e.g. "ORDER BY NULL". -
Returning a row of data in a stored procedure
Please help me remember how to return a row or rows from a pl/sql query in a stored procedure.
I am having a major brain fart.If want to return a resultset from stored procedures see here for an example
http://asktom.oracle.com/~tkyte/ResultSets/index.html -
Counting Rows from a ResultSet
Hi!
If I retreive some information from a database, say by using:
ResultSet RS = Stmt.executeQuery("select * from events");How can I get a value for the amount of rows in this ResultSet?
Thanks!
AlastairAlmost everyone, when they first use ResultSet thinks of it as a container with the data rows already in there, and wonders why there's no size method.
But that's not how they work. A ResultSet, generally, holds only one row at a time. next requests the next row from the database and before next is called the ResultSet doesn't know if another row is going to be available. Indeed the number of rows that qualify for return in the result set may actually change while you are processing it.
Doing the SELECT COUNT(*) request asks the database for the number of rows that match any criteria in the SELECT, but that number may have changed when you actually retrieve the rows. Someone else may have added or removed rows.
Maybe you are looking for
-
I am having an odd problem with my G4. It will not power up. I was using it last night and it just shut off. No crashes or lock ups - it just went black. I hit the power button and nothing. I think it is the power supply though I am not sure. I hit t
-
IMac and Netgear DGND3300v2 on 5Ghz wireless n network problem
Hi guys, I'm can't seem to be able to connect my iMac (bought around Christmas 2010) to my Netgear router on 5Ghz wireless N properly. Everytime I restarted the iMac, it will automatically connect to the 5Ghz network as I have set it up before. Howev
-
Solaris 2.5.1, Sparcstation 20 and a Monitor
Ive got a Sparcstation 20 running Solaris 2.5.1. It has the DB13w3 connector on the back. When I hook up a 20" montor with the correct cable up to the port, the OS never recognizes the display and still displays on my serial terminal (a Wyse 50). Do
-
Solution Manager 3.2 setup
while setting the System Monitoring with transaction DSWP. Solution "Monitoring->System Monitoring". There should be a button "Setup System Monitoring" that is missing. any idea on this? regards shaik
-
What in the world is going on with my battery????
100% this morning, took it to work (I drive around all day in my city). I have 3g and Edge on. At 80%, I had a usage of 1 hour, 6 minutes. Perfect, that's 6 minutes more than what apple states I should get. At 60%, I had a usge of 2 hours, 9 minutes.