Select Distinct rows from 3 tables
I need to retrive information from 3 different tables by applying a specific condition.
I have the following query which works fine for retrieving desired data from 2 tables.
SELECT
a.userId
FROM userGeneral
a inner
join userSpecific
b on a.userId
= b.userId
WHERE
a.userActive
= 1
userId
111
222
333
444
Now I have a third table called userMgr which may contain multiple records for each userId with a corresponding mgrId value. It has a primary key identity column called userRecId and I would like to fetch the
mgrId value corresponding to the MAX(userRecId) for the matching userId.
userRecId | userId | mgrId
1 | 111 | 123
2 | 111 | 234
3 | 111 | 345
4 | 333 | 345
5 | 333 | 456
The resultset should be as follows after joining all the 3 tables.
userId | mgrId
111 | 345
222 | NULL
333 | 456
444 | NULL
Can anyone please help with this query.
I need to retrive information from 3 different tables by applying a specific condition.
I have the following query which works fine for retrieving desired data from 2 tables.
SELECT
a.userId
FROM userGeneral
a inner
join userSpecific
b on a.userId
= b.userId
WHERE
a.userActive
= 1
userId
111
222
333
444
Now I have a third table called userMgr which may contain multiple records for each userId with a corresponding mgrId value. It has a primary key identity column called userRecId and I would like to fetch the
mgrId value corresponding to the MAX(userRecId) for the matching userId.
userRecId | userId | mgrId
1 | 111 | 123
2 | 111 | 234
3 | 111 | 345
4 | 333 | 345
5 | 333 | 456
The resultset should be as follows after joining all the 3 tables.
userId | mgrId
111 | 345
222 | NULL
333 | 456
444 | NULL
Can anyone please help with this query.
try this:
select userId,userRecId,
from userMgr,
(SELECT a.userId, max(a.userRecId)
FROM userGeneral a inner join userSpecific b on a.userId = b.userId
group by a.userId
WHERE a.userActive = 1) table1(userId,userRecId)
where userMgr.userRecId = table1.userRecId
Similar Messages
-
Newbie question: Select one row from table in PL/SQL
Hi,
I want to select one row from the table Employee where Emplyoyee Number is say 200. This is a simple SQL query, but I don't know the equivalent PL/SQL format. I will have 3 out params here - Id itself, Name, Salary. I will then have to populate a java resultset object from these out params.
Later, I'll have to use cursors to retrieve more than one row.
Thanks for any help.Perhaps something like
CREATE OR REPLACE PROCEDURE get_employee( l_id IN OUT employee.id%TYPE,
l_name OUT employee.name%TYPE,
l_salary OUT employee.salary%TYPE )
AS
BEGIN
SELECT name, salary
INTO l_name, l_salary
FROM employee
WHERE id = l_id;
END;Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Selecting duplicate rows from table
Hi all,
How to select the duplicates rows present in the table...SQL> select * from customer;
CUST_ID CUST_NAME LOC
1 Jeff Miami
2 Andrew Michigan
3 Julia Chicago
1 Linda Miami
1 Martha Miami
3 Randy Chicago
3 John Chicago
7 rows selected.
SQL> select * from customer where rowid != (select min(rowid) from customer C where C.cust_id = customer.cust_id);
CUST_ID CUST_NAME LOC
1 Linda Miami
1 Martha Miami
3 Randy Chicago
3 John Chicago
SQL> -
Select Distinct rows from multiple tables
Table 1 is a List of Vendors - VID, PID, VName, VAddress, VPhone
Table 2 is a list of Products - PID, PName, PPrice, PWeight, PColor
I need to produce a list of unique PID's showing the following fields - PID, VName, PName, PColor
So, Here is my failed attempt:
SELECT P.PID, V.VName, P.PName, P.PColor
FROM Products P INNER JOIN Vendors V ON P.PID = V.PID
GROUP BY P.PIDIf you post DDL, sample data and your desired output based on that sample data, someone can probably create a query that does what you want.
And I have to tell you that Table 1 is not a list of vendors unless you have a system where a vendor provides one and only one product - something that is unusual. If your system is one where a vendor should provide any number of products (and if a product
can be provided by any number of vendors), you have some fundamental schema issues to correct.
Lastly, there are sticky posts at the top of the forum that provide suggestions for posting questions. Please have a look - help your readers help you by providing sufficient information. Phrases such as "failed" or "does not work"
do not provide any useful detail. And one good rule of thumb - any time you feel you need to use (or say) distinct in a query is an indication that something somewhere is wrong. It could be a schema issue, a misunderstanding of the schema or the
goal, an incorrect query, etc. There are few instances where distinct is needed in a well-defined and implemented system, IMO. -
How to select distinct rows ..?
Hi all...
I am having one table with many columns. I want to select distinct rows from one column and for each row selected, i want to have one unique number.
For ex:
SELECT DISTINCT SUM(ROWNUM) OVER(ORDER BY C.SPECIFICATION NULLS LAST) AS CODE,
C.SPECIFICATION FROM TABLE_1 C WHERE condition.
In this case, there is a chance of getting duplicate values (1 and 4 rows selected = total 5) and (3 and 2 rows selected = total 5)
i thought of selecting through sub query like this
select rownum, code from (select distinct SPECIFICATION as code from table where ...)
Is there anymore options to get the desired output.
Thanks in advance,
Paltry like this:
select distinct
dense_rank() over(order by c.specification) as code,
c.specification
from table_1 c
where condition -
Display distinct rows from Oracle table without using "DISTINCT" keyword.
How to retrieve distinct rows from oracle table without using 'DISTINCT' keyword in SQL?
Thanks in advance.
MihirWelcome to the forum.
Besides GROUP BY you can use UNIQUE instead of DISTINCT as well, but that's probably not wanted here ;) , and the ROW_NUMBER() analytic:
SQL> create table t as
2 select 1 col1 from dual union all
3 select 1 from dual union all
4 select 2 from dual union all
5 select 3 from dual union all
6 select 4 from dual union all
7 select 4 from dual;
Table created
SQL> select col1 from t;
COL1
1
1
2
3
4
4
6 rows selected
SQL> select distinct col1 from t;
COL1
1
2
3
4
SQL> select unique col1 from t;
COL1
1
2
3
4
SQL> select col1 from t group by col1;
COL1
1
2
3
4
SQL> select col1
2 from ( select col1
3 , row_number() over (partition by col1 order by col1) rn
4 from t
5 )
6 where rn=1;
COL1
1
2
3
4 -
Need of SQL query in selecting distinct values from two tables
hi,
I need a query for selecting distinct values from two tables with one condition.
for eg:
there are two tables a & b.
in table a there are values like age,sex,name,empno and in table b valuses are such as age,salary,DOJ,empno.
here what i need is with the help of empno as unique field,i need to select distinct values from two tables (ie) except age.
can anybody please help me.
Thanks in advance,
RatheeshNot sure what you mean either, but perhaps this will start a dialog:
SELECT DISTINCT a.empno,
a.name,
a.sex,
b.salary,
b.doj
FROM a,
b
WHERE a.empno = b.empno;Greg -
When selecting a row from a view with a nested table I want just ONE entry returned
Does a nested table in a view "EXPLODE" all values ALWAYS no matter the where clause for the nested table?
I want to select ONE row from a view that has columns defined as TYPE which are PL/SQL TABLES OF other tables.
when I specify a WHERE clause for my query it gives me the column "EXPLODED" with the values that mathc my WHERE clause at the end of the select.
I dont want the "EXPLODED" nested table to show just the entry that matches my WHERE clause. Here is some more info:
My select statement:
SQL> select * from si_a31_per_vw v, TABLE(v.current_allergies) a where a.alg_seq
=75;
AAAHQPAAMAAAAfxAAA N00000 771 223774444 20 GREGG
CADILLAC 12-MAY-69 M R3
NON DENOMINATIONAL N STAFF USMC N
U
E06 11-JUN-02 H N
05-JAN-00 Y Y
USS SPAWAR
353535 USS SPAWAR
SI_ADDRESS_TYPE(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NUL
L, NULL)
SI_ADDRESS_TAB()
SI_ALLERGY_TAB(SI_ALLERGY_TYPE(69, 'PENICILLIN', '11-JUN-02', NULL), SI_ALLERGY
TYPE(74, 'SHELLFISH', '12-JUN-02', NULL), SIALLERGY_TYPE(68, 'PEANUTS', '13-J
UN-02', NULL), SI_ALLERGY_TYPE(75, 'STRAWBERRIES', '13-JUN-02', NULL))
SI_ALLERGY_TAB()
75 STRAWBERRIES 13-JUN-02
*******Notice the allergy entry of 75, Strawberries, 13-JUN-02 at the
end. This is what I want not all the other exploded data.
SQL> desc si_a31_per_vw
Name Null? Type
........ Omitted uneeded previous column desc because of metalink
character limit but the view is bigger then this.......
DEPT_NAME VARCHAR2(20)
DIV_NAME VARCHAR2(20)
ADDRESSES SI_ADDRESS_TAB
CURRENT_ALLERGIES SI_ALLERGY_TAB
DELETED_ALLERGIES SI_ALLERGY_TAB
SQL> desc si_allergy_tab
si_allergy_tab TABLE OF SI_ALLERGY_TYPE
Name Null? Type
ALG_SEQ NUMBER
ALG_NAME VARCHAR2(50)
START_DATE DATE
STOP_DATE DATE
SQL> desc si_allergy_type
Name Null? Type
ALG_SEQ NUMBER
ALG_NAME VARCHAR2(50)
START_DATE DATE
STOP_DATE DATECan you explain what do you mean by the following?
"PL/SQL tables (a.k.a. Index-by tables) cannot be used as the basis for columns and/or attributes"There are three kinds of collections:
(NTB) Nested Tables
(VAR) Varrying Arrays
(IBT) Index-by Tables (the collection formerly known as "PL/SQL tables")
NTB (and VAR) can be defined as persistent user defined data types, and can be used in table DDL (columns) and other user defined type specifications (attributes).
SQL> CREATE TYPE my_ntb AS TABLE OF INTEGER;
SQL> CREATE TABLE my_table ( id INTEGER PRIMARY KEY, ints my_ntb );
SQL> CREATE TYPE my_object AS OBJECT ( id INTEGER, ints my_ntb );
/IBT are declared inside stored procedures only and have slightly different syntax from NTB. Only variables in stored procedures can be based on IBT declarations.
CREATE PROCEDURE my_proc IS
TYPE my_ibt IS TABLE OF INTEGER INDEX BY BINARY_INTEGER; -- now you see why they are called Index-by Tables
my_ibt_var my_ibt;
BEGIN
NULL;
END;That sums up the significant differences as it relates to how they are declared and where they can be referenced.
How are they the same?
NTB and VAR can also be (non-persistently) declared in stored procedures like IBTs.
Why would you then ever use IBTs?
IBTs are significantly easier to work with, since you don't have to instantiate or extend them as you do with NTB and VAR, or
Many other highly valuable PL/SQL programs make use of them, so you have to keep your code integrated/consistent.
There's a lot more to be said, but I think this answers the question posed by Sri.
Michael -
Select Distinct Fields from non related table
Hi Experts,
I have to fetch Distinct Fields from table zdcxy along with the fields from the table zvend but there is no primary key forigen key relationship also if I wanted use join condition. I need to move fields from both the table into output file and 1 part I implemented but I am unable to do second part plz any body can help me its argent. below I pasted part of code along with two requirements.
1.Select all data (Location - LIFNR, Descr u2013 ZPLTNAMEC, CJI_CUSTOMER u2013 CJI customer flag) from ZVEND table.
2.Select all distinct DCs and BUs from zdcxy table.
SELECT * FROM ZVENDPLT INTO CORRESPONDING FIELDS OF TABLE IT_VENDPLT.
*select distinct zdc from zdcxy into corresponding fields of table it_map.
*select distinct zbu from zdcxy into corresponding fields of table it_map.
IF SY-SUBRC = 0.
LOOP AT IT_VEND.
MOVE : IT_VENDPLT-LIFNR TO IT_TAB-FIELD1,
IT_VENDPLT-ZPLTNAMEC TO IT_TAB-FIELD2,
IT_VENDPLT-CJI_CUSTOMER TO IT_TAB-FIELD3,
CONCATENATE :IiT_TAB-FIELD1 IT_TAB-FIELD2 IT_TAB-FIELD3 IT_TAB-FIELD4
INTO IT_LOAD-RECORD SEPARATED BY SEPARATOR.
TRANSFER IT_LOAD TO OUT_FILE.
ENDLOOP.
Can any body explain me hw to fetch DC and Bu from the table zdcxy and keep in the same loop of it_vend.
Second thing is that I need to give information about records into second output file hw to do that means I opened one more file and I am unable to move the record history there plz help me.
Thanks in advancePlz any body can help me it's argent.
Thanks
Basu -
Select a row from a table and throw an url
Hi experts,
I'm trying to select a row from a table in Visual Composer. What I need to do it's to click over this row and throw an Url. At the moment, I've added a column with a Pushbutton with the formula to show the link; it works fine. But I need to do it without buttons just selecting the row.
Is there anyboby who knows about that?
Thanks a lot.
BelenHi
To do this you will have to use a data store and a guard condition on the line which is triggered by the select action. You need to store a value in the data store each time a select action is performed. The guard condition should check for this and only perform the action when the value in the data store is greater than 0.
Jarrod Williams -
Select multiple rows from dual table
Is it possible to select multiple rows from dual table using a single select statement.
i.e., i want the out put to be
column_name
1
2
3
4
Edited by: vidya.ramachandra on Dec 14, 2009 8:24 AMAside from the fact you're responding to an old thread...
1002424 wrote:
While using CONNECT BY, I see it always leave behind one row.
Suppose I have a condition based on which I have to generate constant rows like
SELECT 1 FROM DUAL WHERE ROWNUM < N;
Here if N = 0, still it gives out single row.... you are obviously doing something wrong in your code elsewhere, because that SQL statement does not always return a single row...
SQL> SELECT 1 FROM DUAL WHERE ROWNUM < 0;
no rows selected
SQL> -
Easy Question:Select many rows from a table and execute BAPI for these rows
Hi Experts,
I have created one WD project. The WD project fetches some records of backend using BAPI and displays in a table. I have to select some rows from the table and then execute BAPI for selected rows.
How I can select multiple records from the table and then execute another BAPI for selected rows.
Regards,
GaryHi,
In the Node which you binded to the table create one more attribute of type boolean.
For example your node is as below:
//Table Node
TableNode
> Att1
> Att2
> isSelected(boolean) - Newly created attribute for this requirement.
//Result Node contains the elements selected in TableNode
ResultNode
>Att1
>Att2
Now in the table create one more Column with Checkbox as tablecell editor. Now bind this boolean attribute to that check box.
Now in the code you can get the selected rows by user as below:
for(int i=0;i<TableNode().size();i++)
if(wdContext.nodeTableNode().getTableNodeElementAt(i).getIsSelected()==true)
IPrivateTestView.IResultNode element=wdContext.createResultNodeElement();
element.setAtt1(wdContext.nodeTableNode().getTableNodeElementAt(i).getAtt1());
element.setAtt2(wdContext.nodeTableNode().getTableNodeElementAt(i).getAtt2());
wdContext.nodeResultNode().addElement(element);
Regards,
Charan -
Randomly selecting some rows from the database table
Hi can some one help me in selecting some rows from a database table which has around 90,000 rows.
Thanks.One thing you might try is the "sample" clause if you have 8i which is supposed to return a random percentage of the table. Say for example, you have a sequence number on your table as the pkey. Then you might try:
select * from <table_name> where pkey in(select pkey from <table_name> sample(10));
This should give you a random 10 percent of the rows in the table but I tried this once and the results seemed unpredictable. For example it returned a different number of rows each time even though the number of rows in the table didn't change.
Hope this works for you. -
How to efficiently select random rows from a large table ?
Hello,
The following code will select 5 rows out of a random set of rows from the emp (employee) table
select *
from (
select ename, job
from emp
order by dbms_random.value()
where rownum <= 5my concern is that the inner select will cause a table scan in order to assign a random value to each row. This code when used against a large table can be a performance problem.
Is there an efficient way of selecting random rows from a table without having to do a table scan ? (I am new to Oracle, therefore it is possible that I am missing a very simple way to perform this task.)
thank you for your help,
John.
Edited by: 440bx on Jul 10, 2010 6:18 PMHave a look at the SAMPLE clause of the select statement. The number in parenthesis is a percentage of the table.
SQL> create table t as select * from dba_objects;
Table created.
SQL> explain plan for select * from t sample (1);
Explained.
SQL> @xp
PLAN_TABLE_OUTPUT
Plan hash value: 2767392432
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 725 | 70325 | 289 (1)| 00:00:04 |
| 1 | TABLE ACCESS SAMPLE| T | 725 | 70325 | 289 (1)| 00:00:04 |
8 rows selected. -
How to select a row from duplicate set of records?
I want to select a row from a duplicate set of records.
below is the explanation of my requirement.
select * from test_dup;
COL_BILL COL_SERV COL_SYS
b1 s1 c
b1 s1 g
b1 s2 c
b1 s2 g
b2 s2 g
b2 s3 c
b2 s3 g
b3 s3 c
Here what I want is, for a distinct col_sys if col_bill and col_serv is same then I need the row where col_sys='c'
from the above result set I need the following:
b1 s1 c
b1 s2 c
b2 s3 c
I am using the following SQL query which is giving me the correct result set. But it will hamper the performance because there are total 45 columns in the table and total volume is around 50 million.
select * from test_dup where col_bill||col_serv in (
select col_bill||col_serv from (
select col_bill,col_serv,count(*) from test_dup
where col_sys in ('c','g')
group by col_bill,col_serv having count(*) >1)) and
col_sys='c';
Can anyone please provide me the optimize SQL query for the same.Hi,
Another way,
SQL> with test_dup
as
select 'b1' col_bill, 's1' col_serv, 'c' col_sys from dual union all
select 'b1', 's1', 'g' from dual union all
select 'b1', 's2', 'c' from dual union all
select 'b1', 's2', 'g' from dual union all
select 'b2', 's2', 'g' from dual union all
select 'b2', 's3', 'c' from dual union all
select 'b2', 's3', 'g' from dual union all
select 'b3', 's3', 'c' from dual
select col_bill, col_serv, min(col_sys) col_sys
from test_dup
where col_sys in ('c', 'g')
group by col_bill, col_serv
having count( * ) > 1
and count(nullif(col_sys, 'g')) > 0;
CO CO C
b1 s1 c
b2 s3 c
b1 s2 c
3 rows selected.Regards
Peter
Edited by: Peter on Feb 18, 2009 1:10 AM
- Added test data, thanks Karthick
Maybe you are looking for
-
Ipod touch 16gb 2nd gen not recognized by my pc or itunes..
hello. received my Ipod touch 16gb 2nd gen this morning from an ebay seller. i have been trying to get it to work. its screen is ALL BLACK , DOES NOT POWER ON, DOES NOT CONNECT TO MY PC. I have installed latest itunes, my ipod isnt recognized, and it
-
How to call sshr page in custom oaf page
hey everyone, i would like to access the leave of absence page by creating a link on the custom oaf page. So that whenever i click on this link it will open the below page. Below is the function details for the jsp page that i want the link to open i
-
How to get current server node information uses webdynpro?
Hi,everybody! Can I use webdynpro to get the current logined on sever node informaition,such as server node id,server node number.
-
Apps not in pc but are on ipod
took 2nd hd out of old pc (2nd drive only had itunes library)and installed in new pc, all my music and podcasts are there but all my apps are gone, both free and purchased, but they are on my ipod touch, how can i get them back into library?
-
I can't gain access to my install discs and I have tried all the other suggestions for fixing this problem, so I'm thinking reinstallation is the only way. I have access to my serial number but I can't find anywhere that offers a download of CS4 as i