Get query using joins
My Table
employee table
=emp id .. emp name
1 Ravi
2 Kumar
3 Gopal
4 Selvam
5 Raj
6 Sekar
dept table
dept id .. emp id .. salary
1 1 10000
1 2 20000
2 3 30000
2 4 40000
Query
1. Using Join, select Employees not in the dept table
2. select max of salary , dept id , emp_Name from dept group by dept
Kindly provide me the query.
ShanmugaRaj
Looks like homework/exercise given to you. Did you try to write queries by yourself? :)
You may ask your doubts/confusion.
-- 1)
SELECT e.empid
,e.empname
FROM employee e
LEFT JOIN dept d ON e.empid = d.empid
WHERE d.empid IS NULL
--2)
SELECT MAX(d.salary)
,d.deptid
,e.empName
FROM dept d
FULL JOIN employee e ON d.empid = e.empid
GROUP BY d.deptid, e.empname
-Vaibhav Chaudhari
Similar Messages
-
Write the following query using JOIN keyword ?
Qest:
Write the following query using JOIN keyword ?
select ID_category from category_master X
where Exist(select 1 from sub_category Y where
X.ID_category=Y.ID_category)Edited by: 799660 on Oct 3, 2010 6:05 AMselect X.ID_category
from category_master X join (select distinct ID_category from sub_category) Y
on (X.ID_category=Y.ID_category)
/SY. -
Hi,
Please give me the Select query
I have to fetch EBELN,BUKRS,LIFNR,BSART,EKORG,EKGRP,WAERS,WKURS from EKKO and
EBELP,LGORT,MATKL ,WERKS,BEDNR,IDNLF,BPRME,NETPR from EKPO and
MENGE, SAKTO,AUFNR,ANLN1,GSBER,PS_PSP_PNR from EKKN and
LPEIN,EINDT,SLFDT, from EKET.
I have to fetch all the data into an single internal table(Mandatory) by a select query using Joins.
EKKO is having EBELN as primary key
EKPO is having EBELN,EBELP as primary key
EKKN is having EBELN,EBELP as primary key
EKET is having EBELN,EBELP as primary key
Can anybody Please give me the Select query.
With Regards
AjayHi ,
I am sending this sample coed for the Inner joins .Hope this will help you:
Inner joins using 3 tables
Try this :-
SELECT stpostlnr stpoidnrk mastmatnr maramtart stpo~menge
INTO CORRESPONDING FIELDS OF TABLE zmat1 FROM mast
JOIN stpo ON stpostlnr = maststlnr
JOIN mara ON maramatnr = mastmatnr
WHERE stpostlty = 'M' "AND stpoidnrk IN s_matnr
AND mast~werks = 1000.
Here s_matnr is a select-options on the selection-screen.
Or this.
Code:
Select single VbrkBukrs VbrkKunrg Vbrk~Vbeln
VbrkFkdat VbrkBstnk_Vf Vbrk~Zterm
Tvzbt~Vtext
VbakVbeln VbakBstdk
LikpVbeln Likplfdat Likp~Lfuhr
into w_vbrk
from vbrk
inner join Tvzbt on TvzbtZterm = VbrkZterm and
Tvzbt~Spras = sy-langu
Inner join Vbfa as SalesLnk
on SalesLnk~vbeln = pu_vbeln and
SalesLnk~vbtyp_v = c_order
inner join Vbak on VbakVbeln = SalesLnkVbelv
Inner join Vbfa as DeliveryLnk
on DeliveryLnk~vbeln = pu_vbeln and
DeliveryLnk~vbtyp_v = c_Delivery
inner join Likp on LikpVbeln = DeliveryLnkVbelv
where vbrk~vbeln = pu_Vbeln.
This code locates sales, delivery and payment terms info from a billing document number.
or
Here, this one also works fine :
select zfpcdcadivi zfpcdproforma zfpcdfactura zfpcdaniofactura
zfpcdmontousd zfpcdmontoap zfpcdebeln zfpcdinco1
zfpcdlifnr lfa1name1 zcdvsstatus zfpcdconint
into it_lista
from zfpcd inner join zcdvs
on zfpcdebeln = zcdvsebeln
and zfpcdproforma = zcdvsproforma
and zfpcdlifnr = zcdvslifnr
inner join lfa1
on zfpcdlifnr = lfa1lifnr
where zcdvs~status = '04'.
Also Here is another solution that just uses inner joins:
SELECT vbakvbeln vbfaerdat INTO (itab-vbeln, itab-wadat)
FROM ( vbak INNER JOIN vbap
ON vbapvbeln = vbakvbeln )
INNER JOIN vbfa ON vbakvbeln = vbfavbelv
WHERE vbak~kunnr = m_wm AND
vbak~vbtyp = 'C' AND
vbfa~erdat IN s_date AND
vbap~matnr = 'MZ1807F' AND
vbfaposnv = vbapposnr AND
vbfa~vbtyp_n = 'J'.
<REMOVED BY MODERATOR>
Cheers,
Chandra Sekhar.
Edited by: Alvaro Tejada Galindo on Apr 10, 2008 5:20 PM -
Issues with query using joins in 3 tables
I am trying to fetch data from 3 tables (Project,RIsk and Issues) using join. There are Risks associated with some projects and Issues associated with some projects.
ProjectID is primary key in Project table.
RiskID is primary key in risk table. ProjectID is foreign key.
IssueID is primary key in Issue table.ProjectID is foreign Key.
I need the projectname, count of risks for projects, count of issues for projects. I am using joins in all the 3 tables. Issue here is, its giving me double of count of risks and issues for each project.
Please advise how can I get the correct number. I have used the below query,
select p.projectname,count(r.riskid),count(i.issueid) from project as p
left outer join risk as r on p.projectid=r.projecctid
left outer join issue as i on p.projectid=i.projectid
group by
p.projectname
thanksHi All,
I got a new requirement to count, the number of high priority risks as well as high priority issues along with the other details. I modified the below table to include the changes, but I am not getting the desired result. Could you please help?
Original query:
select p.projectname,count(distinct r.riskid), count(distinct i.issueid) from project as p
left outer join risk as r on p.projectid=r.projecctid
left outer join issue as i on p.projectid=i.projectid
group by p.projectname
Modified query:
select p.projectname,count(distinct r.riskid),sum(case when r.riskpriority='high' then 1 else 0 end), sum(case when i.issuepriority='high' then 1 else 0 end),count(distinct i.issueid) from project as p
left outer join risk as r on p.projectid=r.projecctid
left outer join issue as i on p.projectid=i.projectid
group by p.projectnameI should get the desired result as:XYZ,8,1,4,4But I am getting:XYZ,8,4,4,32thanks for the reply. -
Opitmizing sql query using join
Hello all,
I have the following query that needs to be written using Joins. I am not sure if this is the correct place to post this question
Tables used:
1. activities: (a_id, n_id, market, amount, act_type, act_number, act_seq) --the money paid by the registrant for the market.
2. market_reg (a_id, n_id, market, reg_stage) -- for each market there are registrants
3. market (market) -- stores market details
I need to get sum of total_payment_amount using the condition. I know the query is not opitmized and its not the correct way to get info. I was
wondering if you guys can suggest me a query that will pull the information by using joins
SELECT a.a_id, a.n_id, SUM (a.total_payment_amount)
FROM activities a
WHERE a.market = 'marketname'
AND a.a_id||a.n_id IN
(SELECT mr.a_id||mr.n_id
FROM market_reg mr
WHERE mr.market = 'marketname'
AND mr.reg_stage = 'P'
AND mr.n_id <> 0)
AND (a.act_type = 'A'
OR (a.act_type IS NULL
AND a.act_number||act_seq IN
( SELECT a1.act_number||a1.act_seq
FROM activities a1
WHERE a1.market = 'marketname'
GROUP BY a1.act_number||a1.act_seq
HAVING COUNT (a1.act_number||a1.act_seq) = 1)))
GROUP BY a.a_id, a.n_id;
ThanksHi,
I see you have already re-posted this on a more appropriate forum, the SQL and PL/SQL forum.
Thanks,
Gary -
Hi,
my tables structure looks:
Column names:
rhead
bu
sub_bu
report_order
sub_bu_order
q1py
My query is:
select Rhead,bu,Sub_bu,report_order,sub_bu_order,q1py,case
when sub_bu='ISS' then (select q1py from tsg a where a.sub_bu='ESS' and a.rhead=b.rhead)
when sub_bu='TS' then (select q1py from tsg a where a.sub_bu='Services' and a.rhead=b.rhead)
when sub_bu='SW' then (select q1py from tsg a where a.sub_bu='SW' and a.rhead=b.rhead)
else NULL end as q1py_bu,
case
when sub_bu='ISS' then (select q1py from tsg a where a.sub_bu='TSG' and a.rhead=b.rhead)
when sub_bu like 'R&D' and rhead in ('Region owned opex','% of revenue','Region opex','Region opex%') then
(select q1py from tsg a where a.sub_bu like 'TSG' and a.rhead=b.rhead)
else NULL end as q1py_tot from tsg b where report_order=1
Result:
rhead bu sub_bu report_order sub_bu_order q1py q1py_bu q1py_tot
orders ESS ISS 1 1 1162 1778.4 2953.9
here i am using the sub query to produce the result. I need to give the same result by using JOINS.
So any one help me, by using JOINS instead of SUB QUERY and produce the same result
Thanx in advanceHi,
this is my query
select
Rhead,BU,Sub_bu,report_order,sub_bu_order,q1py,
case
when sub_bu='ISS' then (select q1py from tsg a where a.sub_bu='ESS' and a.rhead=b.rhead)
when sub_bu='TS' then (select q1py from tsg a where a.sub_bu='Services' and a.rhead=b.rhead)
when sub_bu='SW' then (select q1py from tsg a where a.sub_bu='SW' and a.rhead=b.rhead)
else NULL end as q1py_bu,
case
when sub_bu='ISS' then (select q1py from tsg a where a.sub_bu='TSG' and a.rhead=b.rhead)
when sub_bu like 'R&D' and rhead in ('Region owned opex','% of revenue','Region opex','Region opex%') then
(select q1py from tsg a where a.sub_bu like 'TSG' and a.rhead=b.rhead)
else NULL end as q1py_tot
last_update from tsg where @condition;
i will use the different conditions. they are
1.sub_bu<>bu and report_order<=8
2.report_order > 8 and report_order<11 and sub_bu not in (‘TSG’)
3.report_order > 10 and report_order <14
4.report_order > 13
i used the above query and getting some time.
so i am using the below query as suggested by forum earlier.
select
Rhead,BU,Sub_bu,report_order,sub_bu_order,q1py,
case
when sub_bu='ISS'
then max(case when sub_bu='ESS' then q1py end) over(partition by rhead)
when sub_bu='TS'
then max(case when sub_bu='Services' then q1py end) over(partition by rhead)
when sub_bu='SW'
then max(case when sub_bu='SW' then q1py end) over(partition by rhead)
end as q1py_bu,
case
when sub_bu='ISS'
then max (case when sub_bu='TSG' then q1py end) over (partition by rhead)
when sub_bu = 'R&D' and rhead in ('Region owned opex','% of revenue','Region opex','Region opex%')
then max(case when sub_bu = 'TSG' then q1py end) over (partition by rhead)
end as q1py_tot, last_update from tsg where @condition;
I am getting better result by this query.
but the problem is this query gives wrong output for first two conditions(1.sub_bu<>bu and report_order<=8
2.report_order > 8 and report_order<11 and sub_bu not in (‘TSG’). The value is not displayed for the virtual column q1py_bu and q1py_tot.
i am getting this warning message too
Warning: Null value is eliminated by an aggregate or other SET operation.
I am not able to find the solution. so plz do help in this..
other than this every thing is fine
thanks -
Hi,
I want to write a SQL statement using Joins. The base table "A" has about 100 fields and the join table "B" a few. I would like to fetch all fields from table "A" and a few from table "B".
Is there a way to write a query wherein I can use "Select * " for table "A" rather than writing all 100 field name in the query? Please keep in mind that I want to use a Join.
Thanks.Hi Thomas,
but if there are some fields which are in both tables, SELECT * will be not sufficient. E.g. fields ERNAM, ERDAT, AENAM, AEDAT are such fields which can occur in more tables. In case that a target area will contain these fields, by * with addition INTO CORRESPONDING FIELDS OF, you are not able to specify from which table these values should be taken. In such case, it can be solved by specifying field list dynamically. If it is not that case SELECT * is sufficient. You should check intersection of common fields for tables you are joining. Thereafter you should decide if you can use SELECT *.
Maybe for better understanding, what exactly I am talking about, look at this example:
TYPES: BEGIN OF ts_data,
ernam TYPE mara-ernam,
END OF ts_data.
DATA: ls_data TYPE ts_data,
ls_mara TYPE mara,
ls_mchb TYPE mchb.
START-OF-SELECTION.
ls_mara-matnr = '1'.
ls_mchb-matnr = ls_mara-matnr.
ls_mara-ernam = 'A'.
ls_mchb-ernam = 'B'.
INSERT mara FROM ls_mara.
INSERT mchb FROM ls_mchb.
SELECT SINGLE * FROM mara INNER JOIN mchb ON mara~matnr = mchb~matnr INTO CORRESPONDING FIELDS OF ls_data.
ROLLBACK WORK.
You as a developer are not able to tell from which table common fields should be selected. But maybe this is really too specific case...
Regards,
Adrian -
Hi,
I am trying to join two tables using joining.
SQL> select * from test10;
ID
1
2
SQL> select * from test11;
ID
1
3
4
My expected output is
ID
1
2
3
4
I am able to do this using "Union"
SQL> select * from test10
2 union
3 select * from test11;
ID
1
2
3
4
But i want to achieve this using join. Please help..
Thanks & Regards,
ArijitHi, Arijit,
The way to do that with a join is FULL OUTER JOIN, like this:
SELECT NVL (t10.id, t11.id) AS id
FROM test10 t10
FULL OUTER JOIN test11 t11 ON t10.id = t11.id
ORDER BY 1
;If that's exactly what you're trying to do, you should stick with the UNION.
FULL OUTER JOIN is good when there are other columns involved. -
Hi all,,,
Assume that my lov is listing (eg empno, ename,dept) when i query for empno. Actually i want to change that empno to deptno ie(deptno,ename,dept) when i queried for empno. How to accomplish this. I think by form personalization we can do ie. BY creating own record group and replacing that with old one, we can do. But i want to know the query used in old record group. How to accomplish this task. plz help me.. Its urgent ... plz... Advance thanks. Any other approach most welcome.. PlzHi all,,,
Assume that my lov is listing (eg empno, ename,dept) when i query for empno. Actually i want to change that empno to deptno ie(deptno,ename,dept) when i queried for empno. How to accomplish this. I think by form personalization we can do ie. BY creating own record group and replacing that with old one, we can do. But i want to know the query used in old record group. How to accomplish this task. plz help me.. Its urgent ... plz... Advance thanks. Any other approach most welcome.. Plz -
Performance tuning in SQL query using join of views
Hi,
Am trying to tune a query of the format
select ........ from view1,view2
where view1.keyfield = view2.keyfield
The base tables of the views view1 and view2 have indexes specified on 'keyfield'.
However, when I do an explain plan of the query, Full table scan of those base tables are performed.
Even tried using Hints in this query to force Oracle to use those indexes, but still not successful.
Any pointers on how to tune this kind of query would be highly welcome.
Regards,
BaishIf your query is really of the same form as you posted, then full table scans then a hash or merge join may be the most efficient plan.
You are asking for all of the rows from view1 and the matching rows from view2, because of this, Oracle dedcided that the cost of full table scans using multi-block reads is cheaper than using single block reads to get the rowids from the index, then single block reads to get the rows from the table.
FULL SCAN <> BAD
John -
Query Using Joins.Please Help
Hi,
A Query please
I have a Customer table and an Order Table
The customer can place multiple orders
Create Table Customers
(Cust_id number(2),
cust_name varchar2(15),
constraint pk_custid PRIMARY KEY(Cust_id)
Create Table Orders
(Order_no number(2),
Cust_id number(2),
order_status varchar2(1),
constraint pk_orderno PRIMARY KEY(order_no),
constraint fk_custid FOREIGN KEY(cust_id)
REFERENCES Customers(cust_id)
)Now,the Customer table has a single record
whereas the Order Table has multiple records
for the same customer.
SQL> Select * from Orders
ORDER_NO CUST_ID ORDER_STATUS
1 1 P
2 1 PI'd like to view the different orders for that same customer
Using a simple Join DOES NOT give the right output:
SQL> Select C.cust_id,C.cust_name,
2 O.order_no,O.order_status
3 From Customers C,Orders O
4 where C.cust_id = O.order_no;
CUST_ID CUST_NAME ORDER_NO O
1 ABCD 1 PThere are 2 records in the Orders Table?
How to view both the records from Orders Table?
Do I need to use the EXISTS clause?
Can someone please help?Well, I would have thought that you would join C.cust_id with the O.cust_id (and not O.order_no)???
SQL> Select C.cust_id,C.cust_name,
2 O.order_no,O.order_status
3 From Customers C,Orders O
4 where C.cust_id = O.order_no; -
Error in select query using join
hi all
please help.
The follwing code givs this error....
select skb1-bukrs ska1-ktoks skb1-saknr skb1-waers skb1-xsalh skb1-xopvw skb1-xkres
into corresponding fields of table it_skab1
from ( skb1
OUTER JOIN ska1 on ska1-saknr=skb1-saknr ) .
*Error while executing....*
Program ZABHI_FIREPORT
"(" has no closing ")".
Please guide me for the correct syntax.
Thank u.hi,
use this code n check
tables: ska1,skb1.
data: begin of it_skab1 occurs 0,
bukrs like skb1-bukrs,
ktoks like ska1-ktoks,
saknr like skb1-saknr,
waers like skb1-waers,
xsalh like skb1-xsalh,
xopvw like skb1-xopvw,
xkres like skb1-xkres,
end of it_skab1.
select skb1~bukrs
ska1~ktoks
skb1~saknr
skb1~waers
skb1~xsalh
skb1~xopvw
skb1~xkres
from skb1 left outer join ska1 on skb1saknr = ska1saknr
into corresponding fields of table it_skab1 up to 10 rows.
loop at it_skab1.
write: / it_skab1-bukrs,it_skab1-ktoks,it_skab1-saknr,it_skab1-waers,it_skab1-xsalh,
it_skab1-xopvw,it_skab1-xkres.
endloop.
n let me knw is ur doubt cleared
rgds
shivraj
Edited by: ShivrajSinha on May 27, 2009 8:27 AM -
Using join and batch reading in the same query
Hi,
I wonder if it is possible to use "Joining" and "batch reading" in the same query.
For example I Have
A -> 1-1 B
A -> 1-1 B
B -> 1-M C
This is the case where I have two separate 1-1 relationships to the same class B from A. Toplink 10.0.3 can manage it nicely through joining.
Now, I would like to read a set of As (with its 2 Bs) and all Cs for each B.
It seems that the following configuration does not work:
A -> 1-1 B (use joining)
A -> 1-1 B (use joining)
B -> 1-M C (Batch read)
Any help would be greatly appreciated
Tony.James,
Would you be so kind to look at the following code?
Am I formulating it correctly to achieve my desired behavior?
Trip.class -> 1-1 PickupStop
Trip.class -> 1-1 DropoffStop
PickupStop and DropoffStop extend Stop and use same table (STOP)
Stop -> 1-M StopEvents
I would like to fetch all Trips, with their Stops and all StopEvents in 2 queries:
1. Trip joined with Stop
2. Batchread StopEvents
Code:
ReadAllQuery raq = new ReadAllQuery(Trip.class);
Expression qexp1 = new ExpressionBuilder();
Expression qexp2 = new ExpressionBuilder();
raq.addJoinedAttribute("pickupStop");
raq.addJoinedAttribute("dropoffStop");
raq.addBatchReadAttribute(qexp1.get("pickupStop").get("vStopEvents"));
raq.addBatchReadAttribute(qexp2.get("dropoffStop").get("vStopEvents")); -
Deciphering column names in a join query using jdbc
hi all....
I am making a database adapter for a generic report generater. This adapter would be forming queries involing various tables. There are two ways of doing it . I fire an sql on parent table to get the keys and then go to child table for each one of them or i form a join query to get desired result.
i want to go with the later approach where my query would be forming a join. The problem comes when table involved in this join has columns with the same name. for eg if a column "NOTE" is there in table A as well as table B on which i have a join. Resultset returns me with two "NOTE" columns and i cannot recognize which one belongs to which table.
all API calls including getString("Note") seems to be referring to the first occurence of "Note" column.
Also getTableName() and getSchemaName() APIs on resultsetMetadata doesnt return in anything in case of joins.
Any pointers would be most appreciated.
cheers
vivekthanks for suggesting this solution ... though i had thought of the same onece .... unfortunately i cannot implement something like this coz out of the result set i have to instantiate an object hierarchy depending on the schema ....
this also puts me in a doubt whether i can use join in my case.
for eg ... .
lets say we have a customer talbe and and address table which has one to many relationship .... one contact can have multiple addresses.
Assuming a contanct "Joe Bloggs" having 3 addresses ...a query like following
select contact.firstname contactfirstname , address.streetname addressstreetname from contact , address where contact.contactid = address.contactid
this would return me 3 rows and i can also recognize various columns with their aliases ..
but i would lose an important fact that i have to create one java object for contact class and 3 instances for addresses which i have to return finally.
this means that i would like to return an object hierarchy with one contact object and 3 address object underneath it linked with contactid.
Any other suggestions after reading the complete requirement are most welcome ...sorry for not puting the entire thing at first.
i guess the only soln left is to visit contact and address table separately. :( -
How can I perform this kind of range join query using DPL?
How can I perform this kind of range join query using DPL?
SELECT * from t where 1<=t.a<=2 and 3<=t.b<=5
In this pdf : http://www.oracle.com/technology/products/berkeley-db/pdf/performing%20queries%20in%20oracle%20berkeley%20db%20java%20edition.pdf,
It shows how to perform "Two equality-conditions query on a single primary database" just like SELECT * FROM tab WHERE col1 = A AND col2 = B using entity join class, but it does not give a solution about the range join query.I'm sorry, I think I've misled you. I suggested that you perform two queries and then take the intersection of the results. You could do this, but the solution to your query is much simpler. I'll correct my previous message.
Your query is very simple to implement. You should perform the first part of query to get a cursor on the index for 'a' for the "1<=t.a<=2" part. Then simply iterate over that cursor, and process the entities where the "3<=t.b<=5" expression is true. You don't need a second index (on 'b') or another cursor.
This is called "filtering" because you're iterating through entities that you obtain from one index, and selecting some entities for processing and discarding others. The white paper you mentioned has an example of filtering in combination with the use of an index.
An alternative is to reverse the procedure above: use the index for 'b' to get a cursor for the "3<=t.b<=5" part of the query, then iterate and filter the results based on the "1<=t.a<=2" expression.
If you're concerned about efficiency, you can choose the index (i.e., choose which of these two alternatives to implement) based on which part of the query you believe will return the smallest number of results. The less entities read, the faster the query.
Contrary to what I said earlier, taking the intersection of two queries that are ANDed doesn't make sense -- filtering is the better solution. However, taking the union of two queries does make sense, when the queries are ORed. Sorry for the confusion.
--mark
Maybe you are looking for
-
The newsletter is for nurses. I save "blurbs" from articles w' the link all month long. I then pull up the form for the newsletter and (while on AOL) I used to diminish the form copy the "blurb" and enlarge the form and paste the article. Although th
-
How to delete the queries in BW Production which are no longer existing.
Hi, How to delete the queries in BW production which are no longer existing in DEV. 1. I tried Using RSZDELETE in Production it is not getting deleted and the below message given. Query object 4A7V83T3RB4ABIOKSDJT2HWDL is blocked. Deletion has been
-
L440 Externer Monitor an Display Port Ruhezustand
Hallo, wenn ich über Display Port mit einem externen Monitor (Asus PB 248) arbeite, dann das L440 in Ruhezustand versetze und ich es wieder starte, wird immer das eingebaute Display eingeschaltet. Der externe Monitor muss jedes Mal über "Win+P" aktiv
-
Hi all I am trying to clear a customer invoice with vendor invoice. We have the normal customer vendor setting and clearing against each other. However if i simulate, the profit center picked up while clearing the two items using F-02 is completely d
-
Mapping between SAP work process and db2 application/applications ?
Hi, I want to identify what db2 application(s), maps to particular SAP work process.(when I mean db2 application I mean entry in "list applications" command output) Both db2 "list applications" and SAP work process lists PIDS of processes they belog.