What Does Just 'JOIN' Statement Do W/o Inner Or Outer Or Cross In Front
Jul 26, 2002There is some code that I am looking at. It is like this
SELECT a.Name, p.Name
FROM applicant a
JOIN Pending p
ON a.ID = p.ID
Thanks list.
There is some code that I am looking at. It is like this
SELECT a.Name, p.Name
FROM applicant a
JOIN Pending p
ON a.ID = p.ID
Thanks list.
Hello
Can any one tell me the difference between Cross Join, inner join and outer join in laymans language
by just taking examples of two tables such as Customers and Customer Addresses
Thank You
Hello,
I have a query:
Select a.ID as ID1, b.ID as ID2 from Table1 a
left outer join Table2 b ON b.AID=a.ID AND b.deleted=0
So, when b.deleted=1, I get a.ID as ID1 and null as ID2
I need to put "b.deleted=0" into WHERE part, like:
Select a.ID as ID1, b.ID as ID2 from Table1 a
left outer join Table2 b ON b.AID=a.ID
WHERE b.deleted=0
, but then I get no results, when b.deleted=1.
Please, help. I have no way out - WHERE part and that's it (because a select is made dynamicly).
Take the following scenario:
We have two tables that have somewhat of a parent-child relationship. We are trying to use a SQL-92 outer join that returns the same results as a TSQL *= outer join. The difficulty we are having is that some of the parent records do not have any corresponding child records, but we still want to see those parent records with 0 (zero) for the count. How can we accomplish this with a SQL-92 compliant join (if it is even possible)? In the query results below, we would like the first set of results.
Thanks in advance for any help.
-David Edelman
Test script below, followed by results
===========================================
create table parent (p_id int NOT NULL)
go
create table child (p_id int NOT NULL, c_type varchar(6) NULL)
go
insert parent values (1)
insert parent values (2)
insert parent values (3)
insert parent values (4)
insert parent values (5)
insert parent values (6)
insert parent values (7)
insert parent values (8)
insert parent values (9)
insert parent values (10)
go
insert child values (1, 'AAA')
insert child values (1, 'BBB')
insert child values (1, 'CCC')
insert child values (2, 'AAA')
insert child values (4, 'AAA')
insert child values (4, 'DEF')
insert child values (4, 'AAA')
insert child values (4, 'BBB')
insert child values (5, 'AAA')
insert child values (5, 'AAA')
insert child values (6, 'AAA')
insert child values (7, 'AAA')
insert child values (7, 'BBB')
insert child values (7, 'CCC')
insert child values (7, 'DDD')
insert child values (10, 'AAA')
insert child values (10, 'CCC')
go
select p.p_id, count(c.p_id) as num_rows
from parent p, child c
where p.p_id *= c.p_id
and c.c_type in ('AAA', 'BBB')
group by p.p_id
select p.p_id, count(c.p_id) as num_rows
from parent p left outer join child c on p.p_id = c.p_id
where c.c_type in ('AAA', 'BBB')
group by p.p_id
=========================================
Results:
(T-SQL *= outer join)
p_id num_rows
----------- -----------
1 2
2 1
3 0
4 3
5 2
6 1
7 2
8 0
9 0
10 1
(SQL-92 outer join)
Warning: Null value eliminated from aggregate.
p_id num_rows
----------- -----------
1 2
2 1
4 3
5 2
6 1
7 2
10 1
what is difference between outer apply and outer join ,both return rows from left input as well as right input . isnt it?
View 3 Replies View RelatedHello
I've a table with these values:
Cod_Lingua - Des_Lingua
------------------------------
ITA Italian
GER German
ENG English
FRA French
and another table with product/description
ProductID - Cod_Lingua - Description
-------------------------------------------
1 ITA Mia Descrizione
1 ENG My Description
I've this SELECT:
SELECT Tab_Lingue.Cod_Lingua, Descrizioni_Lingua.Description
FROM Descrizioni_Lingua RIGHT OUTER JOIN Tab_Lingue ON Tab_Lingue.Cod_Lingua=Descrizioni_Lingua.Cod_Lingua
WHERE Descrizioni_Lingua.ProductID=1
I get these results:
ITA - Mia Descrizione
ENG - My Description
I don't want this. I'd like to have this:
ITA - Mia Descrizione
ENG - My Description
GER - (null)
FRA - (null)
How can I get the second result set?
Thanks for your support.
full outer joins and cross joins not working!?!?
am using vc++2005, ADO, and MSAccess 2003. MS "documentation" straight out of the VC++2005 help facility at
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vdt01/html/419ef633-5a89-41a2-aefe-03540afc9112.htm
provided the following code samples for different types of joins
inner join
Code:
SELECT title, pub_name
FROM titles INNER JOIN
publishers ON titles.pub_id = publishers.pub_id left join
Code:SELECT titles.title_id,
titles.title,
publishers.pub_name
FROM titles LEFT OUTER JOIN publishers
ON titles.pub_id
= publishers.pub_idright join
Code:SELECT titles.title_id,
titles.title,
publishers.pub_name
FROM titles RIGHT OUTER JOIN publishers
ON titles.pub_id
= publishers.pub_idfull join
Code:SELECT titles.title_id,
titles.title,
publishers.pub_name
FROM titles FULL OUTER JOIN publishers
ON titles.pub_id
= publishers.pub_idjoin
Code:
SELECT *
FROM authors CROSS JOIN publishers i created two MSAccess Tables:
Merge1:
K1 x
---- ----
a 1
b 2
c 3
Merge2:
K1 x
---- ----
b 20
c 30
d 40
e 50
and executed the following code to test the different joins. the first three joins worked but the last two did not. would appreciate any insight. DBM is an instance of an AccessDBManager class i have written to encapsulate interactions with Access DBs.
Code:
DBM.SQLExtractString = "select * from Merge1 INNER JOIN Merge2 on Merge1.K1 = Merge2.K1";
DBM.SQLExtract();
s.Format(_T("%d"),DBM.SQLExtractRecords);
MessageBox(s,_T(""),MB_OK);this worked - 2 records returned (K1 = b,c)
Code:DBM.SQLExtractString = "select * from Merge1 LEFT OUTER JOIN Merge2 on Merge1.K1 = Merge2.K1";
DBM.SQLExtract();
s.Format(_T("%d"),DBM.SQLExtractRecords);
MessageBox(s,_T(""),MB_OK);this worked - 3 records returned (K1 = a,b,c)
Code:DBM.SQLExtractString = "select * from Merge1 RIGHT OUTER JOIN Merge2 on Merge1.K1 = Merge2.K1";
DBM.SQLExtract();
s.Format(_T("%d"),DBM.SQLExtractRecords);
MessageBox(s,_T(""),MB_OK);this worked - 4 records returned (K1 = b,c,d,e)
Code:DBM.SQLExtractString = "select * from Merge1 FULL OUTER JOIN Merge2 on Merge1.K1 = Merge2.K1";
DBM.SQLExtract();
s.Format(_T("%d"),DBM.SQLExtractRecords);
MessageBox(s,_T(""),MB_OK);this did not work - 0 records returned instead of 5 (K1 should = a,b,c,d,e)
Code:DBM.SQLExtractString = "select * from Merge1 CROSS JOIN Merge2";
DBM.SQLExtract();
s.Format(_T("%d"),DBM.SQLExtractRecords);
MessageBox(s,_T(""),MB_OK);this did not work - 0 records returned instead of 20 (5 * 4)
appreciate any ideas/comments to get the last two joins to work.
thanks - j
I was writing a query using both left outer join and inner join. And the query was ....
SELECT
S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
INNER JOIN Production.Categories AS C
[code]....
However ,the result that i got was correct.But when i did the same query using the left outer join in both the cases
i.e..
SELECT
S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
LEFT OUTER JOIN Production.Categories AS C
ON C.categoryid = P.categoryid)
ON
S.supplierid = P.supplierid
WHERE
S.country = N'Japan';
The result i got was same,i.e
supplier country productid productname unitprice categorynameSupplier QOVFD Japan 9 Product AOZBW 97.00 Meat/PoultrySupplier QOVFD Japan 10 Product YHXGE 31.00 SeafoodSupplier QOVFD Japan 74 Product BKAZJ 10.00 ProduceSupplier QWUSF Japan 13 Product POXFU 6.00 SeafoodSupplier QWUSF Japan 14 Product PWCJB 23.25 ProduceSupplier QWUSF Japan 15 Product KSZOI 15.50 CondimentsSupplier XYZ Japan NULL NULL NULL NULLSupplier XYZ Japan NULL NULL NULL NULL
and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.
Scenario:
OLEDB source 1
SELECT ...
,[MANUAL DCD ID] <-- this column set to sort order = 1
...
FROM [dbo].[XLSDCI] ORDER BY [MANUAL DCD ID] ASC
OLEDB source 2
SELECT ...
,[Bo Tkt Num] <-- this column set to sort order = 1
...
FROM ....[dbo].[FFFenics] ORDER BY [Bo Tkt Num] ASC
These two tasks are followed immediately by a MERGE JOIN
All columns in source1 are ticked, all column in source2 are ticked, join key is shown above.
join type is left outer join (source 1 -> source 2)
result of source1 (..dcd column)
...
4-400-8000119
4-400-8000120
4-400-8000121
4-400-8000122 <--row not joining
4-400-8000123
4-400-8000124
...
result of source2 (..tkt num column)
...
4-400-1000118
4-400-1000119
4-400-1000120
4-400-1000121
4-400-1000122 <--row not joining
4-400-1000123
4-400-1000124
4-400-1000125
...
All other rows are joining as expected.
Why is it failing for this one row?
I have a merge join (full outer join) task in a data flow. The left input comes from a flat file source and then a script transformation which does some custom grouping. The right input comes from an oledb source. The script transformation output is asynchronous (SynchronousInputID=0). The left input has many more rows (200,000+) than the right input (2,500). I run it from VS 2005 by right-click/execute on the data flow task. The merge join remains yellow and the task never finishes. I do see a row count above the flat file destination that reaches a certain number and seems to get stuck there. When I test with a smaller file on the left it works OK. Any suggestions?
View 3 Replies View Relatedhello, i am running mysql server 5 and i have sql syntax like this:
select
sales.customerid as cid,
name,
count(saleid)
from
sales
inner join
customers
on
customers.customerid=sales.customerid
group by
sales.customerid
order by
sales.customerid;
it works fine and speedy. but when i change inner join to right join, in order to get all customers even there is no sale, my server locks up. note: there is about 10000 customers and 15000 sales.
what can be the problem?
thanks,
Given a table of building components e.g. floors, walls, etc, etc:
create table component_multiplier_table
(
system_code char(4),
system_component_code char(3),
function_code char(4),
component_multiplier dec(7,6)
)
Where function_code is the function of the area e.g. Auditorium, Classrom, etc, etc. And not all components are available for all functions e.g. Carpeting is available for Classrooms but not Power Plants or Warehouses.
I need to self join the above table to itself on system_code and system_component_code and find out which rows are missing from each side.
A query that I've been banging away at with no success is:
SELECT c1.*, c2.*
FROM [dbo].[component_multiplier_table] c1 FULL OUTER JOIN [dbo].[component_multiplier_table] c2
ON (c1.system_component_code = c2.system_component_code) AND (c1.[system_code] = c2.[system_code])
WHERE c1.function_code = '2120' AND c2.[function_code] = '2750' AND (c1.[system_code] IS NULL OR c2.system_code IS NULL);
I added the is null conditions, no joy. I've tried every flavor of outer join w/o success.
Could any T-SQL gurus out there help me figure out how to do this in a set before I start coding
DECLARE crsr CURSOR
Thanks.
Anyone know why using
SELECT *
FROM a LEFT OUTER JOIN b
ON a.id = b.id
instead of
SELECT *
FROM a LEFT JOIN b
ON a.id = b.id
generates a different execution plan?
My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".
Any enlightenment is very appreciated.
Thanks
good morning
I wanna to put a sub query in the cross join like that
SELECT *
FROM table1
CROSS JOIN (select field
from table2
cross join table3)
but i got this error
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ')'.
can anyone help me!!!!
I have the following structure with remote select permissions; I cannot create temp tables or use stored procs:
tblEvent with event_pk, eventName
tblReg with reg_pk, event_fk, person_fk, organization_fk
I'm currently using a case statement to get counts for these categories:
case
when c.person_fk is Null and c.organization_fk is not null then 'Employer'
when c.person_fk is Not Null and c.organization_fk is null then 'Individual'
when c.person_fk is not Null and c.organization_fk is not null then 'Both'
else 'Unknown'
end
But I need some kind of count (0) for every category. I've used a cross-join, group by in the past - but what do you do if you don't have a table? For example, the end result when selecting event_pk=(112,113) would be:
event_pk, myCount, countCat
112 0 Employer
112 1 Individual
112 4 Both
112 0 Unknown
113 5 Employer
113 0 Individual
113 0 Both
113 2 Unknown
Thanks for any help,
jb
I am wanting to show Total Quantity of Presentations2 for each EmpVol and TypeofPresentation, even if there are no Presentations done in TypeofPresentation or if an Employee did not do any Presentations.
I am close with the query below - but not getting back exactly what I want - Ideas.
SELECT ISNULL(Presentations2.Quantity, 0) AS Quantity, TypeofPresentation.Typeofpresforrpt, EmpVol_2.LastName, EmpVol_2.FSSTVOLUNTEER
FROM Presentations2 INNER JOIN
EmpVol ON Presentations2.ID = EmpVol.ID RIGHT OUTER JOIN
TypeofPresentation ON Presentations2.TypePresINT = TypeofPresentation.TypePresINT CROSS JOIN
EmpVol AS EmpVol_1 CROSS JOIN
EmpVol AS EmpVol_2
GROUP BY TypeofPresentation.Typeofpresforrpt, EmpVol_2.LastName, EmpVol_2.FSSTVOLUNTEER, ISNULL(Presentations2.Quantity, 0)
HAVING (EmpVol_2.FSSTVOLUNTEER = N'FSST')
Thanks,
I have the following 2 tables:(BATCHES)BatchID [int] KEYID [int]OrderID [int]Action1DateTime [datetime]Action2DateTime [datetime]Action3DateTime [datetime]Action4DateTime [datetime]Action5DateTime [datetime]Action6DateTime [datetime]Action7DateTime [datetime]Action8DateTime [datetime](ORDERS)OrderID [int] KEYProductionLineID [int]RecipeID [int]OrderAmount [int]Batches.Action1DateTime to Batches.Action8DateTime can have several entrieseach day.I need a query to count all Batches.Action1DateTime to allBatches.Action8DateTime for each day in a specified period.I also need to specifically use where clauses for Orders.OrderID and/orOrders.RecipeID.I need the data to draw a graph for each ActionXDateTime as a function ofdate.Any help appreciated./Henrik
View 3 Replies View RelatedHello
I have to retrieve a cross join between languages and language-skills for more person in a matrix (grid) report.
E.g. i like to ritrieve the TOP 2 people in each "cell" of the grid (order by name).
There are 3 people in cell "ITALIAN / very good".
So i have to retrieve only the top 2.
In table tEmployee i have the people names (john, anna, michael)
In table tLanguage i have all language (english, italian, german)
And in table tLanSkill i have the language rating (bad, good, very good)
bad
good
very good
Englisch
Michael
John
Anna
Italian
John
Michael
Anna
German
Anna
THX for your help.
ciao, michele
How can I achieve the same effect as a cross join (since the merge operator doesn't have a cross join)?
Situation is this... a flat file has some header and footer information that I need to keep and attach to each row. So for simplicity sake of an example lets just say header has only 1 thing we care about - a row that says DATE=01/01/06.
I take the file and run a split to split into "Date" "Data" and "other" (other has all the throwaway rows in header and footer I don't care about). Then I use a derived column object to get all the columns out of the "Data". Finally I want to add that Date metadata back to every row in the data...
I thought this would be an easy thing to do.. but I can't seem to figure out how to duplicate that Date info into every row.. Hopefully I am overlooking something simple.
Thanks in advance.
StaffTable
StaffID (int ,PK)
StaffFullName(vnchar(50))
DepartmentTable
DepartmentID (int,PK)
StaffID (int,FK)
DepartmentName(vnchar(50))
it seems when I use SELECT * FROM StaffTable,DepartmentTable
it returns a lot of wrong data.(I guess, the right data is just in 10%, 90% is wrong)
So , is this mean, in a real industry software project, no one would use cross join?
Hi folks, this is my first time here... i hope that you can help me with this query
I have two query and one table
Queries
Q1-Training - List of training
Q2-Group - Groups that must take the training
Table
T1 - Training_Group
Here a query example using SELECT * FROM
Q1
Code Name
-----------------------------------
AD0041 Advance SQL
BE0012 Beginner SQL
NE0001 Newbie SQL
...
Q2
Group_Name Group_Code
-----------------------------------
Administration ADMIN
Directors 456
John Smith 555666
...
T1
Code Level Group_Code
-----------------------------------
AD0041 1 ADMIN
AD0041 2 456
AD0041 3 555666
BE0012 2 456
NE0001 1 ADMIN
Here's my problem :
I need to make a report that look like that
(as training) (Group_Code) --> dynamic column
^^^^^^ ^^^^^^
Training ADMIN 456 555666
-------------------------------------
AD0041 1 1 1
BE0012 0 1 0
NE0001 1 0 0
I did it in ACCESS with TRANSFORM and PIVOT.
But how i do that in SQL Server 8.0 ?^
Thanks in advance for your solution or hints... i'll be back tomorrow morning
Best regards
David
Oi! What follows is a hypothetical situation, but it is a totally analogous to a real problem Im having, but provides an easier model to understand.
Imagine that you have database-driven battleship game and its time to render the board. Also imagine that you have to render more than one board and that the ships are all the size of one point on the grid.
One sql result you need is a list of all the points on the grid, regardless of whether or not there is a ship on it. This will make rendering much easier for you, because you can simply look at the record index to determine if a ship is present. The data that is stored about the position of the ships consists of one record containing the grid index and ship name.
One possible way to retrieve this data is to build a table that you will not change which contains a record for each point on the grid. Is it possible to union or join on this table to retrieve a list of results that contain both unoccupied locations and occupied ones?
Here is what I've come up with, but it contains results that have a null location when there are no ship records:
SELECT
Grids.GridID,
Ships.GridLocation,
Ships.Name
FROM
Grids
FULL OUTER JOIN Ships
ON Ships.GridID = Grids.GridID
WHERE
Grids.PlayerID = 1
UNION-- (**not** UNION ALL)
SELECT
Grids.GridID,
GridLocations.GridLocation,
(SELECT ShipName FROM Ships WHERE GridID = Grids.GridID AND GridLocation = GridLocations.GridLocation)
FROM
GridLocations, Grids
WHERE
Grids.PlayerID = 1
Hello there,
I have 2 tables:
Table: Leads
------------------
ID LDate ClientID
1 04/02/2004 101
2 04/03/2004 103
3 04/04/2004 104
....
Table: Tracking
------------------
ID TDate ClientID Shown Clicked
1 04/02/2004 101 3 2
2 04/03/2004 103 5 4
3 04/04/2004 101 3 9
....
I need a query to display results for any Client ID like this:
Date Leads Shown Clicked
=============================
04/02/2004 1 3 2
04/04/2004 0 3 9
.....
=============================
The following query doesn't work, it display 1 in leads column instead of 0:
select t.Tdate, count(l.id) as Leads, sum(t.shown) as Views
from tracking t left outer join Leads l on r.clientid = t.clientid
where l.clientid = 101
and l.Ldate >= 'April 2,2004'
and t.Tdate >= 'April 2,2004'
group by t.Tdate
Thanks a lot for your time and help in advance.
Here's the lookup table, tblLookup:
Task
SubTask
Subset
Superset
Description
And here's the more voluminous table, tblRecords, to which I need to join that:
Task
SubTask
Acct_cat
Actual_Amount
Budgeted_Amount
The problem is that the Task data in tblLookup consists only of the first 5 chars of the same kind of data in tblRecords (e.g., if a field on that record in tblRecords says "BILLYGOAT", that field in tblLookup is entered only as "BILLY").
How do I match them up?
Thanks.
Hello,
I am having problems with an outer join statement.
I have written a procedure that tests a table for missing and corrupt data and
to test my procedure, I take a table with 100% correct entries and corrupt them by hand. Then I test if my repaird data is looking like the correct data did.
To do the test, I copy the correct data into a temp table "copy", join it with the "repaired" table and check if any fields look different. The problem is, that i don't get the missing data. The statement is looking like this:
select o.*,'#',k.* from repaired o right outer join copy k on
(str(o.a) + 'A' + str(o.b) + 'A' + str(o.c) =str(k.a)+ 'A' + str(k.b) + 'A' + str(k.c) )
where
o.D<>k.D or
o.E<>k.E or
o.F<>k.F or
...
I have dont the concatenation because I thougt, that a join with 3 fields could be responsible for not finding the missing data in table "copy".
Before that it looked like:
... on (o.a=k.a and o.b=o.b and o.c = k.c) where ...
In table "copy" is a record missing that is in table "repaired".
Why is my statement not printingout that missing record?
Shouldn't be an outer join exactly what I have to use for finding missing data?
I anybody can help me, I would be very happy.
Sven
Why do we need a Right outer join, when we get the same results by swapping the order in which tables are specified in a Left join?
View 9 Replies View RelatedOk....I have 3 tables.
Entity
--------
name
entity_key
Address
----------
street
zip
mailing_flag
entity_key
Phone
--------
phone_number
phone_type_key
entity_key
I want to see all of the Entity records with their corresponding Address and Phone records. (select e.name, a.street, a.zip, p.phone_number)But only show the Address record for that Entity if the mailing_flag is 'Y' and I only want to see the Top 1 Phone record where the phone_type_key = 'Home'. If the above criteria isn't met I just want to see nulls for the Address and Phone records.
My problem is getting ALL the Entity records to return. It only wants to give me the Entity records that have Address or Phone associated with them. That and somehow showing the Top 1 phone record for the Entity are my issues.
Any help would be much appreciated......Thanks!
Hello,
I have the following script which is *sort of working* !!
The problem I have is that I need to add an outer join to one of the tables and I don't know where to add it or what the syntax is.
Basically, anyone who has an 'STRA' role in the contacts_roles table does not usually have an email address (shown as communications.notes). However, because I don't have any outer joins in place, the script is ignoring everyone who has an 'STRA' role and only pulling back those with an 'STRE' role.
Any help would be much appreciated as to how and where I put my outer join.
Thanks so much.
Jon
SELECT contacts.label_name, contact_positions.position, contact_roles.role, contact_roles.organisation_number, communications.notes, organisations.status, organisations.name, addresses.address, addresses.town, addresses.county, addresses.postcode
FROM bmf.dbo.addresses addresses, bmf.dbo.communications communications, bmf.dbo.contact_positions contact_positions, bmf.dbo.contact_roles contact_roles, bmf.dbo.contacts contacts, bmf.dbo.organisations organisations
WHERE contact_roles.contact_number = contacts.contact_number AND communications.contact_number = contacts.contact_number AND organisations.organisation_number = contact_roles.organisation_number AND addresses.address_number = organisations.address_number AND contact_positions.contact_number = contacts.contact_number AND contact_positions.organisation_number = organisations.organisation_number AND ((contact_roles.role In ('STRE','STRA')) AND (organisations.status In ('BRAN','FULL','HOLD')))
ORDER BY organisations.name
Help!
I have a query that runs fine with 2 outer joins, but I am using "*=" syntax and this won't work for SQL 2005.
I am replacing with 'LEFT OUTER JOIN'... I can get it to work okay for first join, but not when I add the second
Any idea
Josephine
Hi i am having problem getting a resultset in a specific format which i wanted
i am suppose to get this:
team_id|Student|student_not_yet_submitted
Team 1|A,B,C|A
Team 2|D,E,F|NULL
Where (team_id, student) and student_not_yet_submitted are from different tables. Issue of concatenating aside (i am able to do this with java loop), I derived them like this:
1st select=select team_id, student_name from team, student where (....) to get the 1st 2 columns.
To get the 3rd column,
my second select is the same as 1st select but it has an additional condition based on results from 1st select stmt (using the team_id passed in)
2nd select=select team_id, student_name from team where (..... and student_name not in (a 3rd query stmt with result based on team_id from 1st select statement))
i am trying to use left outer join on student_name to join the 2 stmt together, but i am stuck because the 2nd select statement (or rather the 3rd inner query) requires input from the 1st. is there a more efficient way of doing this?
Below is my query. I am a relative novice to SQL. I'd like to rewrite this with joins. All should be inner joins except for the last one Aritem to shmast. That should be a left outer join because not all of our invoices (in the Aritem tables) have actually been shipped.
How would I do this? I have already read through 2 SQL books, but the examples they give are much simpler than what I need to do. Here's the Query:
SELECT DISTINCT Ardist.fcacctnum, Ardist.fcrefname, Ardist.fccashid,
Ardist.fcstatus, Armast.fcinvoice, Armast.fbcompany, Armast.fcustno,
Ardist.fddate, Ardist.fnamount * -1 as fnAmount,
glmast.fcdescr,
shmast.fcstate,
slcdpm.fcompany as CompanyName
FROM ardist, glmast, armast, slcdpm, shmast, aritem
WHERE Glmast.fcacctnum = Ardist.fcacctnum
AND Armast.fcinvoice = SUBSTRING(Ardist.fccashid,8,20)
AND Ardist.fnamount <> 0
AND ((Ardist.fcrefname = 'INV' OR Ardist.fcrefname = 'CRM' OR Ardist.fcrefname = 'VOID')
AND Glmast.fccode = 'R')
AND armast.fcustno = slcdpm.fcustno
AND armast.fcinvoice = aritem.fcinvoice
AND left(aritem.fshipkey,6) = shmast.fshipno
what is difference between inner join and outer join also right and left join can you explain with simple example(because i m fresher) and the query which are there in previous forum will work for the mainframe environment?
View 1 Replies View RelatedIn my (admittedly brief) sojurn as an SQL programmer I've often admired"outer joins" in textbooks but never really understood their use. I'vefinally come across a problem that I think is served by an outer join.-- This table stores the answer to each test questionCREATE TABLE TestResults (studentIdvarchar (15)NOT NULL,testIdintNOT NULL REFERENCES Tests(testId),qIdintNOT NULL REFERENCES TestQuestions(qId),responseintNOT NULL REFERENCES TestDistractors(dId),CONSTRAINT PK_TestResultsPRIMARY KEY NONCLUSTERED (testId, studentId, qId),)-- This table defines which questions are on which testsCREATE TABLE TestQuestions_Tests (testIdintNOT NULL REFERENCESTests(testId),qIdintNOT NULL REFERENCESTestQuestions(qId),)(Table Tests contains housekeeping information about a particular test,TestQuestions defines individual questions, TestDistractors lists thepossible responses.)In schematic form, the simplest form of my problem is to find all thequestions that haven't been answered. That would be:SELECT tqt.qIdFROM TestResults AS trRIGHT OUTER JOIN TestQuestions_Tests AS tqtON tr.testId = tqt.testId AND tr.qId = tqt.qIdWHERE tr.qId is NULLSo far I think this is pretty straightforward and an efficient solution.Agreed?But my real problem is a little bit more complex. What I really want toknow is "for a given student, on a given test, which questions haven'tbeen answered?"So now I have:SELECT tqt.qIdFROM TestResults AS trRIGHT OUTER JOIN TestQuestions_Tests AS tqtON tr.testId = tqt.testId AND tr.qId = tqt.qIdWHERE tqt.testId = '1' AND tr.studentId = '7' AND tr.qId IS NULLIs this the canonical form of the solution to my problem? It seems tome like it is generating a whole slew of rows and then filtering them.Is there a more elegant or efficient way to do it?-- Rick
View 6 Replies View Related