SQL Select 1 record from each department
assume emp table
1- i want to retrive 1 employee from each department
2- 2 from each
3- total 20 records 1st employee from 1st dept, 2nd from 2nd, 3rd from 3rd, 4th from 1st , 5th from 2nd and so on
Edited by: Fakhr-e-Alam on Aug 10, 2011 3:20 AM
Is this homework? Remember to give OTN Forums full credit when you hand in your assignment.
This is how to do the first one: you shoudl be able to figure out the others from here.
SQL> select e.*
2 from emp e
3 where (empno, 1) in
4 ( select x.empno
5 , row_number() over (partition by x.deptno
6 order by x.hiredate )
7 from emp x )
8 order by e.deptno
9 /
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7782 BOEHMER MANAGER 7839 09-JUN-81 2450 10
7369 CLARKE CLERK 7902 17-DEC-80 800 20
7499 VAN WIJK SALESMAN 7698 20-FEB-81 1600 300 30
8101 PSMITH 03-DEC-10 40
8060 VERREYNNE PLUMBER 8061 08-APR-08 4000 50
SQL>In this case, the employees are ordered on the basis of HIREDATE, so the longest serving employees are selected from each department. Other definitions of "first" will require different sorting criteria. You know your own business rules.
Cheers, APC
Edited by: APC on Aug 10, 2011 10:33 AM
Similar Messages
-
Query to retrieveonly three emplyee details from each department-v 10.2.0.4
Hi all,
Need query to retrieve only 3 employees from each department.
Order can be same as server retrieve.
Eg. If dept 10 has 5 employees, query should return only 3 employee details (emp#, deptno, salary).
If dept 20 has only 1 employee then should return one emp details.
Thanks.with t as (
select e.*,
row_number() over(partition by deptno order by 1) rn
from emp e
select *
from t
where rn <= 3
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO RN
7782 CLARK MANAGER 7839 09-JUN-81 2450 10 1
7839 KING PRESIDENT 17-NOV-81 5000 10 2
7934 MILLER CLERK 7782 23-JAN-82 1300 10 3
7369 SMITH CLERK 7902 17-DEC-80 800 20 1
7876 ADAMS CLERK 7788 23-MAY-87 800 20 2
7902 FORD ANALYST 7566 03-DEC-81 3000 20 3
7499 ALLEN SALESMAN 7698 20-FEB-81 1500 300 30 1
7698 BLAKE MANAGER 7839 01-MAY-81 1500 30 2
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 3
9 rows selected.
SQL> SY. -
How can I select random records from one column
How can I random select 400 records from a column contains more than 500,000 records? And how long will it take in oracle? Thanks.
here is one option: (just change 5 to suit your needs...)
SQL>select * from (
2 select object_name
3 from all_objects
4 order by dbms_random.random
5 ) where rownum < 5
6 /
OBJECT_NAME
UTL_SYS_COMPRESS
GV_$LOG_HISTORY
GV_$LOGMNR_LOGS
WWV_FLOW_THEME_7
SQL>/
OBJECT_NAME
WWV_FLOW_UPGRADE_REPORT
WRI$_ADV_SQLT_STATISTICS_PK
V_$DATABASE
GV_$SERVICEMETRIC
SQL>/
OBJECT_NAME
WWV_FLOW_CREATE_FLOW_API
WRH$_SERVICE_WAIT_CLASS_BL
EXU8SNAPL
GV$SERVICEMETRIC_HISTORY
SQL> well, regarding how long will it take... it depends from lots of variables...
Cheers,
Andrea -
I have several disks with many comedy routines;I want to select a few from each disk to make one single disk for my personal use.How?
Copy the routines into a new folder on your hard drive. Then burn the folder to a new blank disc using Disk Utility.
-
How to select multiple records from a TREE in the table
HI,
I have a tree structure which is in the table.When I open the node of the tree,all the subnodes are coming as one-one records in the table.I want to slect multiple record from this table.I applied onLeadSelect for this table,I can select only 1 record from the table.
Can any one plz suggest me how to select multiple records from the table so that I can get all the data of those selected record.
Regards
-SandipRashmi/Kukku,
First of all, Thanks for your help!
Is there any other way in which we can access tables other than using BAPIs or RFCs?
In my case, there is a table structure which has to be updated with values after validating a key. i don't think there is any RFC available now. do i need to create bapi/rfc for that?
Krishna Murthy -
Why sql select 'Hello'||'world012345678' from dual; cause error?
I have problem and your help to solve it would be very much appreciated.
Can anybody tell why the result is so different for the following two sql-sentence in SQL/PLus?
sql>select 'Hello'||'world012345678' from dual;
sql>select 'Hello'||'world0123456789' from dual;
sql>select 'Hello'||'world012345678' from dual;
Result:
select 'Hello'||'world012345678' from dual
ERROR at line 1:
ORA-00600: internal error code, arguments: [17182], [158346180], [], [], [],
sql>select 'Hello'||'world0123456789' from dual;
Helloworld0123456789
I found that if the length of one string equals 14, then the sql will failed as the first sentence.If you need to check the validity of DUAL then you have:
Select count(1) from DUAL ;
NOT
Select * from DUAL;
If you find more than 1, then
delete from dual;
insert into dual values ('x') ;
commit;
Then, try you offending query. -
Displaying the selected multiple records from node using onleadselect event
Hi all,
How to display the selected multiple records from node to node using onleadselect event.
i came to know tht to fulfill this requirement i need to use the method get_selected_elements,
how to use this method in my event??
sreeHi Sree,
Try below code..
DATA : lo_nd_it_lips TYPE REF TO if_wd_context_node, // This is first node
lo_el_it_lips TYPE REF TO if_wd_context_element,
ls_it_lips TYPE wd_this->Element_it_lips,
lt_it_lips TYPE wd_this->Elements_it_lips.
DATA: wa_temp TYPE REF TO if_wd_context_element,
lt_temp TYPE wdr_context_element_set.
* navigate from <CONTEXT> to <IT_LIPS> via lead selection
lo_nd_it_lips = wd_context->path_get_node( path = `ZRETURN_DEL_CHANGE.CHANGING_3.IT_LIPS` ).
CALL METHOD lo_nd_it_lips->get_selected_elements
EXPORTING
INCLUDING_LEAD_SELECTION = ABAP_true
RECEIVING
set = lt_temp.
DATA lo_nd_pack_mat TYPE REF TO if_wd_context_node. //Second Node
DATA lo_el_pack_mat TYPE REF TO if_wd_context_element.
DATA ls_pack_mat TYPE wd_this->Element_pack_mat.
DATA lt_pack_mat TYPE wd_this->Elements_pack_mat.
* navigate from <CONTEXT> to <PACK_MAT> via lead selection
lo_nd_pack_mat = wd_context->get_child_node( name = wd_this->wdctx_pack_mat ).
lo_nd_pack_mat->get_static_attributes_table( importing table = lt_pack_mat ).
LOOP AT lt_temp INTO wa_temp.
CALL METHOD wa_temp->get_static_attributes
IMPORTING
static_attributes = ls_it_lips.
ls_pack_mat-vbeln = ls_it_lips-vbeln.
ls_pack_mat-material = ls_it_lips-matnr.
ls_pack_mat-vgbel = ls_it_lips-vgbel.
append ls_it_lips to lt_unpack.
CLEAR ls_pack_mat.
ENDLOOP.
Cheers,
Kris. -
SQL to group the records and apply logic to pick one record from each group
Hi Friends,
I am looking for a query to group the records on certain columns in a table and then from each group I want to pick only one record based on certain rules.
May be having data laid out will make my point more clear to you. Here you go :
CREATE TABLE AD_LIST
FILE_NAME VARCHAR2(50 BYTE),
ACTIVITY_START DATE,
ACTIVITY_END DATE,
DIVISION VARCHAR2(50 BYTE),
ITEM_CODE VARCHAR2(50 BYTE),
MULT NUMBER,
RETAIL NUMBER,
AD_PAGE VARCHAR2(1 BYTE),
FORECAST NUMBER,
MEMO VARCHAR2(50 BYTE)
INSERT INTO AD_LIST VALUES ('FILE_1','01-APR-2010','15-APR-2010','B',1111,5,10,'A',10,'This must be in my result');
INSERT INTO AD_LIST VALUES ('FILE_1','01-APR-2010','15-APR-2010','B',1111,1,1,'B',15,'Must not be in my result');
INSERT INTO AD_LIST VALUES ('FILE_1','01-APR-2010','15-APR-2010','B',1111,6,15,'C',11,'Must not be in my result');
INSERT INTO AD_LIST VALUES ('FILE_1','16-APR-2010','30-APR-2010','N',1111,4,20,'D',40,'Must not be in my result');
INSERT INTO AD_LIST VALUES ('FILE_1','16-APR-2010','30-APR-2010','N',1111,5,15,'E',30,'Must not be in my result');
INSERT INTO AD_LIST VALUES ('FILE_1','16-APR-2010','30-APR-2010','N',1111,1,2,'F',20,'This must be in my result');
CREATE TABLE PAGE_RANK
AD_PAGE VARCHAR2(1 BYTE),
RANK NUMBER
INSERT INTO PAGE_RANK VALUES ('A',1);
INSERT INTO PAGE_RANK VALUES ('B',2);
INSERT INTO PAGE_RANK VALUES ('C',3);
INSERT INTO PAGE_RANK VALUES ('D',4);
INSERT INTO PAGE_RANK VALUES ('E',5);
INSERT INTO PAGE_RANK VALUES ('F',6);
COMMIT;
SELECT * FROM AD_LIST
FILE ACTIVITY ACTIVITY ITEM AD
NAME START END DIV CODE MULT RETAIL PAGE FORECAST MEMO
FILE_1 4/1/2010 4/15/2010 B 1111 5 10 A 10 This must be in my result
FILE_1 4/1/2010 4/15/2010 B 1111 1 1 B 15 Must not be in my result
FILE_1 4/1/2010 4/15/2010 B 1111 6 15 C 11 Must not be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 4 20 D 40 Must not be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 5 15 E 30 Must not be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 1 2 F 20 This must be in my resultNow, from the table AD_LIST I want to group the records based on FILE_NAME, ACTIVITY_START, ACTIVITY_END, DIVISION, ITEM_CODE.
So in my example here we have 2 set of records grouped based on the columns specified.
Also we have one more table, PAGE_RANK, which has a rank corresponding to each ad_page number. Here 1 is higher rank than 2. Hence ad page 'A' takes priority over 'B'. Similarly for all other ad pages.
Now, we need to pick one ad from each group of ads by determining the highest ranked ad page within the group and the value for mult and retail must be replaced with the value that has min(retail/mult). So, using the above data we will have the one having ad page = 'A' and ad page = 'D' as the final results since they have highest ad page rank in their group.
The value for mult and retail values for ad_page 'A' = min (10/5 , 1/1, 15/6) = 1,1(mult,retail).
The value for mult and retail values for ad_page 'D' = min (20/4 , 15/5, 2/1) = 1,2(mult,retail).
Finally I have this query below
SELECT a.file_name,
a.activity_start,
a.activity_end,
a.division,
a.item_code,
FIRST_VALUE (a.mult) OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY (a.retail /
a.mult))
mult,
FIRST_VALUE (a.retail) OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY (a.retail /
a.mult))
retail,
FIRST_VALUE (a.ad_page) OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY (b.RANK))
ad_page,
a.forecast,
a.memo
FROM ad_list a, page_rank b
WHERE a.ad_page = b.ad_pageThis query is giving me all the records but with the values what I wanted in Ad_Page, Mult and Retail columns.
How can I pick only one from each group.
I am getting this FILE ACTIVITY ACTIVITY ITEM AD
NAME START END DIV CODE MULT RETAIL PAGE FORECAST MEMO
FILE_1 4/1/2010 4/15/2010 B 1111 1 1 A 15 Must not be in my result
FILE_1 4/1/2010 4/15/2010 B 1111 1 1 A 10 This must be in my result
FILE_1 4/1/2010 4/15/2010 B 1111 1 1 A 11 Must not be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 1 2 D 20 This must be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 1 2 D 30 Must not be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 1 2 D 40 Must not be in my resultBut I want this FILE ACTIVITY ACTIVITY ITEM AD
NAME START END DIV CODE MULT RETAIL PAGE FORECAST MEMO
FILE_1 4/1/2010 4/15/2010 B 1111 1 1 A 10 This must be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 1 2 D 20 This must be in my resultI have to run this query for thousands of such group combination.
Hope some one can throw some light on this query.
Thanks in advance,
Raj.Frank,
You are marvelous.
That is what I was expecting, but basically I want to display the row with highest page rank which is 'A' and 'D' in this case.
So I have changed my query as below using yours :
WITH mainq AS
(SELECT a.file_name,
a.activity_start,
a.activity_end,
a.division,
a.item_code,
FIRST_VALUE (a.mult) OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY (a.retail /
a.mult))
mult,
FIRST_VALUE (a.retail) OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY (a.retail /
a.mult))
retail,
--FIRST_VALUE (a.ad_page) OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY (b.RANK))
a.ad_page,
a.forecast,
a.memo,
ROW_NUMBER () OVER (PARTITION BY a.file_name, a.activity_start, a.activity_end, a.division, a.item_code ORDER BY b.RANK)
AS r_num
FROM ad_list a, page_rank b
WHERE a.ad_page = b.ad_page)
SELECT *
FROM mainq a
WHERE r_num = 1
FILE ACTIVITY ACTIVITY ITEM AD
NAME START END DIV CODE MULT RETAIL PAGE FORECAST MEMO
FILE_1 4/1/2010 4/15/2010 B 1111 1 1 A 10 This must be in my result
FILE_1 4/16/2010 4/30/2010 N 1111 1 2 D 40 Must not be in my resultMy apologies that I gave you wrong forecast and memo values in my earlier post.
But that is what I wanted and your input greatly helped me to save lot of time by using in one single query.
Earlier I was using cursor to do that and it was not doing any good performance wise.
Thanks to every body for your time and your efforts.
I appreciate it.
Have fun.
~Raj -
Select one record for each member of the group
Hi,
am having a table where in i will be having data for so many group members. i need to fetch data for a particular group members whose number of rows of data may be more in numbers (but i want only one row of data for each member of the group)
here is the query for fetching all rows of data
select RI.RESOURCE_NAME,TR.MSISDN,TR.ADDRESS1_GOOGLE, TR.MSG_DATE_INFO, FROM TRACKING_REPORT TR, RESOURCE_INFO RI
WHERE TR.MSISDN IN (SELECT MSISDN FROM RESOURCE_INFO WHERE GROUP_ID ='1' AND COM_ID=2 ) AND RI.MSISDN=TR.MSISDN
order by MSG_DATE_INFOoutput of this query is...
>
ddd 12345 13-Mar-10 19:43:03
eee 54321 Tamil Nadu, India 13-Mar-10 19:39:48
ddd 12345 13-Mar-10 19:32:58
eee 54321 Tamil Nadu, India 13-Mar-10 19:30:07
ddd 12345 13-Mar-10 19:23:08
eee 54321 Tamil Nadu, India 13-Mar-10 19:20:14
fff 98765 13-Mar-10 19:19:22
ddd 12345 13-Mar-10 19:13:01
eee 54321 Tamil Nadu, India 13-Mar-10 19:09:50
ddd 12345 13-Mar-10 19:02:56
eee 54321 tn,ind 13-Mar-10 18:59:49
ddd 12345 13-Mar-10 18:53:08
eee 54321 tn,ind 13-Mar-10 18:49:50
ddd 12345 13-Mar-10 18:42:56
eee 54321 tn,ind 13-Mar-10 18:39:50
ddd 12345 13-Mar-10 18:33:00
eee 54321 tn,ind 13-Mar-10 18:29:50
ddd 12345 13-Mar-10 18:22:54
eee 54321 tn,ind 13-Mar-10 18:19:50
ddd 12345 13-Mar-10 18:12:56
eee 54321 tn,ind 13-Mar-10 18:09:50
ddd 12345 13-Mar-10 18:02:54
eee 54321 tn,ind 13-Mar-10 18:00:02
fff 98765 Tamil Nadu, India 13-Mar-10 17:59:26
fff 98765 Tamil Nadu, India 13-Mar-10 17:54:26
ddd 12345 13-Mar-10 17:52:56
eee 54321 tn,ind 13-Mar-10 17:49:50
fff 98765 Tamil Nadu, India 13-Mar-10 17:49:25
fff 98765 Tamil Nadu, India 13-Mar-10 17:44:26
ddd 12345 13-Mar-10 17:42:56
>
from this output i want only one latest record for each member(ddd,eee,fff). i.e
>
ddd 12345 13-Mar-10 19:43:03
eee 54321 Tamil Nadu, India 13-Mar-10 19:39:48
fff 98765 13-Mar-10 19:19:22
>
how to modify the query to achieve this...?Hi,
This is not giving the result which i want...
table is
CREATE TABLE TRACKING_REPORT
ID NUMBER,
MSISDN NUMBER(12) NOT NULL,
X NUMBER(15,8) NOT NULL,
Y NUMBER(15,8) NOT NULL,
TIME_STAMP DATE,
MSG_DATE_INFO DATE DEFAULT sysdate,
ADDRESS1_GOOGLE VARCHAR2(400 BYTE),
ADDRESS2_GOOGLE VARCHAR2(400 BYTE),
ADDRESS_MLINFO VARCHAR2(400 BYTE),
REQ_ID VARCHAR2(30 BYTE)
CREATE TABLE RESOURCE_INFO
RESOURCE_ID NUMBER,
MSISDN NUMBER,
RESOURCE_NAME VARCHAR2(25 BYTE),
ADDRESS VARCHAR2(100 BYTE),
COM_ID VARCHAR2(20 BYTE),
ADMIN_ID NUMBER,
TIME_STAMP DATE DEFAULT SYSDATE,
GROUP_ID NUMBER
) -
Retreving the selected substring records from existing records.
Hi all,
SQL> select * from temp;
C1 C2
1 abcdef
2 efbcda
3 axyz
4 abedcd
I would like to retrieve only the records which have substring 'CD' from the available records..
Any help.
Regards,
~ sriWill the "cd" be fixed - i.e. is it always 'cd' you're looking for?
If so, a function-based index on INSTR(c2,'cd') might help, then your query could be
where INSTR(c2,'cd') > 0
and use the index. -
Java.sql : Cannot retrieve records from Oracle 9i with JDK 1.5
I think I'm doing everything right, but still the following code does not
return any rows. I have the classpath set correctly and ojdbc14.jar in
the path. I'm using jdk 1.5.
What am I missing? Any help greatly appreciated. Thanks!
Connection conn = null;
String serverName = "MySvr";
String portNumber = "1521";
String sid = "mySID";
String myURL = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
logger.writeLog("URL: " + myURL);
String username = "scott";
String password = "tiger";
String query = "select 'test' from dual";
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(myURL, username, password);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(query);
logger.writeLog("Cur Row : " + rs.getRow());
-----> returns 0
while (rs.next()) {
------> throws java.lang.NullPointerException
}I think I'm doing everything right, but still the following code does not
return any rows. JDBC didn't change from 1.4 to 1.5, so that's a red herring. It's you, not the JVM.
I have the classpath set correctly Really? A system CLASSPATH environment variable? I'd say that's wrong. Better to use the -classpath option on javac.exe when you compile and java.exe when you run.
and ojdbc14.jar in the path. You'd better mean CLASSPATH and not PATH. CLASSPATH is for the Java class loader; PATH is for the operating system. Don't get the two confused.
I'm using jdk 1.5. Irrelevant here.
What am I missing? Any help greatly appreciated. Thanks!I think you're using ResultSet incorrectly, because it's never null.
Try this:
// I'd externalize this so you could change it on the fly.
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@MySvr:1521:mySID";
// I hope you're not using the default username and password for real
String username = "scott";
String password = "tiger";
logger.writeLog("URL: " + url);
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
String sql = "select 1 from dual";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
int value;
while (rs.next())
value = rs.getInt(1);
catch (SQLException e)
e.printStackTrace();
finally
// I'd put all these in a utility class
try { if (rs != null) rs.close(); } catch (SQLException e) { logger.writeLog("could not close result set"); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { logger.writeLog("could not close statement"); }
try { if (conn != null) conn.close(); } catch (SQLException e) { logger.writeLog("could not close connection"); }
}Note: close your resources in a finally block. It's important, especially if you don't want to run out of Oracle cursors.
% -
Select common records from 3 tables
Hi - I'm trying to construct a select statement from the following tables(see example)
|Customer__| Product_| Shop__|
|-----------------|---------------|-------------|
|Customer1 | Milk____| Dairy___|
|Customer2 | Cream__| Dairy___|
|Customer3 | Milk____| Dairy___|
|Customer1 | Trainers_| Sports__|
|Customer2 | Football_| Sports__|
REQUIRED RESULT SET: Milk, Cream.
Basically I want to select all of the Products (no duplicates) where EVERY customer(1, 2 & 3) have bought a from a common shop type: i.e 'Trainers' and 'Football' should not be selected as Customer3 has not bought any goods from a sports store.
This looks like it should be easy but my SQL isn't the best ;-)
I'd really appreciate any help you could give!!
Cheers!SQL> with example as (
2 select 'Customer1' customer, 'Milk' product, 'Dairy' shop from dual union all
3 select 'Customer2' customer, 'Cream' product, 'Dairy' shop from dual union all
4 select 'Customer3' customer, 'Milk' product, 'Dairy' shop from dual union all
5 select 'Customer1' customer, 'Trainers' product, 'Sports' shop from dual union all
6 select 'Customer2' customer, 'Football' product, 'Sports' shop from dual
7 )
8 select distinct product from example where shop in
9 (
10 select shop from example group by shop
11 having count(*) = (select count(distinct customer) from example)
12 )
13 /
PRODUCT
Cream
Milk
SQL> -
Selecting single record from multiple record based on date
Hi experts,
I have a table which contains the multiple records for single ID No. Now i have to select single record which contains the latest date.
here is the structure
Name Null Type
ID_P NUMBER
NAME_P VARCHAR2(12)
DATE_P TIMESTAMP(6)
Records
1 loosi 22-AUG-13 01.27.48.000000000 PM
1 nammi 26-AUG-13 01.28.10.000000000 PM
2 kk 22-AUG-13 01.28.26.000000000 PM
2 thej 26-AUG-13 01.28.42.000000000 PM
now i have to select below 2 rows how can write select qurie for this?
1 loosi 26-AUG-13 01.27.48.000000000 PM
2 thej 26-AUG-13 01.28.42.000000000 PMHi,
You can use the analytic ROW_NUMBER function.
I don't have a copy of your table, so I'll use scott.emp to illustrate. In scott.emp, there may be multiple rows for a single job. To display just 1 row per job, the row with the most recent hiredate:
WITH got_r_num AS
SELECT empno, job, deptno, hiredate -- Or whatever columns you want
, ROW_NUMBER () OVER ( PARTITION BY job
ORDER BY hiredate DESC
) AS r_num
FROM scott.emp
-- WHERE ... -- If you need any filtering put it here
SELECT * -- Or list all columns except r_num
FROM got_r_num
WHERE r_num = 1
What results do you want in case of ties? Depending on your requirements, you may want to add tie-breaking expressions to the analytic ORDER BY clause, and/or use RANK instead of ROW_NUMBER.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
Point out where the query above is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
If you modify the query at all, post your modified version.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002 -
How to get two top salaries from each department
select st.staff_name,st.dept_code,
st.staff_sal
from staff_master st
where staff_code in ((select staff_code
from staff_master s
where staff_sal=(select max(staff_sal) from staff_master where dept_code=st.dept_code))
union
select staff_code from staff_master st where staff_sal=
(select max(staff_sal) from staff_master where dept_code=st.dept_code and staff_sal < (select max(staff_sal) from staff_master where dept_code=st.dept_code)))
order by st.dept_code;You can use RANK, DENSE_RANK or even ROW_NUMBER based on your need. Below is an example using DENSE_RANK. I have used EMP table available in SCOTT schema.
SQL> select * from emp order by deptno, sal desc;
EMPNO ENAME JOB MGR HIREDATE SAL COM DEPTNO ID
7782 CLARK MANAGER 7839 09-JUN-13 12450 0 10
7839 KING PRESIDENT 17-NOV-13 5000 0 10
7788 SCOTT ANALYST 7566 19-APR-87 13000 0 20
7369 SMITH CLERK 7902 02-APR-13 12975 0 20
7566 JONES MANAGER 7839 02-APR-13 12975 0 20
7876 ADAMS CLERK 7788 23-MAY-87 11101 0 20
7698 BLAKE MANAGER 7839 01-MAY-13 12850 0 30
7499 ALLEN SALESMAN 7698 20-FEB-13 11600 300 30
7844 TURNER SALESMAN 7698 08-SEP-13 11500 0 30
7521 WARD SALESMAN 7698 22-FEB-13 11250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-13 11250 1400 30
11 rows selected.
SQL> select *
2 from (
3 select e.*
4 , dense_rank() over(partition by deptno order by sal desc) emp_rank
5 from emp e
6 )
7 where emp_rank <= 2;
EMPNO ENAME JOB MGR HIREDATE SAL COM DEPTNO ID EMP_RANK
7782 CLARK MANAGER 7839 09-JUN-13 12450 0 10 1
7839 KING PRESIDENT 17-NOV-13 5000 0 10 2
7788 SCOTT ANALYST 7566 19-APR-87 13000 0 20 1
7369 SMITH CLERK 7902 02-APR-13 12975 0 20 2
7566 JONES MANAGER 7839 02-APR-13 12975 0 20 2
7698 BLAKE MANAGER 7839 01-MAY-13 12850 0 30 1
7499 ALLEN SALESMAN 7698 20-FEB-13 11600 300 30 2
7 rows selected.
SQL> -
SQL query - select one row from each date group
Hi,
I have data as follows.
Visit_Date Visit_type Consultant
05/09/2009 G name1
05/09/2009 G name2
05/09/2009 G name3
06/09/2009 I name4
07/09/2009 G name5
07/09/2009 G name6
How to select data as follows
05/09/2009 G name1
06/09/2009 G name4
07/09/2009 G name5
i.e one row from every visit_date
Thanks,
MK Nathan
Edited by: k_murali on Oct 7, 2009 10:44 PMAre you after this (one row per date per visit_type)
with dd as (select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name1' Consultant from dual
union all
select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name2' Consultant from dual
union all
select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name3' Consultant from dual
union all
select to_date('06/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name4' Consultant from dual
union all
select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name5' Consultant from dual
union all
select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name6' Consultant from dual
union all
select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'F' Visit_type, 'name7' Consultant from dual)
select trunc(visit_date) visit_date, visit_type, min(consultant)
from dd
group by trunc(visit_date), visit_type
order by trunc(visit_date);
VISIT_DAT V MIN(C
09/MAY/09 G name1
09/JUN/09 G name4
09/JUL/09 G name5
09/JUL/09 F name7or are you after only one row per date?:
with dd as (select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name1' Consultant from dual
union all
select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name2' Consultant from dual
union all
select to_date('05/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name3' Consultant from dual
union all
select to_date('06/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name4' Consultant from dual
union all
select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name5' Consultant from dual
union all
select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'G' Visit_type, 'name6' Consultant from dual
union all
select to_date('07/09/2009','MM/DD/YYYY') Visit_Date, 'F' Visit_type, 'name7' Consultant from dual)
select trunc(visit_date) visit_date, min(visit_type) visit_type, min(consultant)
from dd
group by trunc(visit_date)
order by trunc(visit_date);
VISIT_DAT V MIN(C
09/MAY/09 G name1
09/JUN/09 G name4
09/JUL/09 F name5
Maybe you are looking for
-
How can I get my Panasonic 3D TV and BluRay Player to go online using Time Capsule?
So I've extended my home network using my Time Capsule so that I have a stronger signal in different parts of my home. My Time Capsule isn't hard wired to the modem, but I'm now getting a stronger signal in parts of my house that never had good signa
-
IPhone calendar not syn in icloud
When I input new event from my iphone and ipad, the new event don't syn to iCloud!!!
-
Word 2007 complex autofill date feature
I need to write the date in a heading (within the text body) and I need Word 2007 to autofill the consecutive dates into the following headings in the document. Example: I want to be able to write "Monday, 2/ 02" and I want Word to autofill "Tuesday
-
I pushed a button by accident and suddenly they werent there and now I cant browse, check history, settings etc
-
Hello gurus, I am trying to create a delivery for an STPO (Stock transfer PO) using VL10B. When I execute it, it shows up the PO. Then when I select the PO and click back ground, its dumping. The error is - The termination occurred in the ABAP prog