SQL ORACLE Joining two queries together as one? - sql

thanks in advance for your help.
I have a set of tables like this.
Also, here is a semi-accurate ERD to see what's going on.
I need to list all donations made by individual Alumni, and businesses. I need the first/last name and IDs present.
The following code returns all I need about the Alumni donors:
SELECT DonationID, Donation.AlumniID, BusinessID_FK, DONATIONDATE, Value, Alumnus.FirstName, Alumnus.LastName
FROM DONATION
JOIN Alumnus
on Donation.AlumniID=Alumnus.alumniid;
And the following code returns all I need about the Business donors:
SELECT * FROM DONATION
JOIN BusinessSponser
on Donation.businessid_fk=businesssponser.businessid;
Furthermore, the following query returns all the IDs, however no First/Last names:
SELECT * FROM DONATION
LEFT JOIN BusinessSponser
on Donation.businessid_fk=businesssponser.businessid;
So my question is, how can I merge these queries together as one? My intention is to create a view that would display the final result.
Thanks in advance for your help.

The outer join is a SQL technique which allows us to join rows from one table with some rows from another table. In your case you have two optional tables so you need two left outer joins:
select donationid
, donation.donationdate
, donation.value
, donation.alumniid
, alumnus.firstname
, alumnus.lastname
, donation.businessid
, businesssponser.businessname
from donation
left outer join alumnus
on donation.alumniid=alumnus.alumniid;
left outer join businesssponser
on donation.businessid_fk=businesssponser.businessid;

Related

sql natural join and cross join should give same output

We're currently starting SQL in school ... so I'm very beginner.
Now we got a task that says:
Write a SQL-query which gives the same output like the following query. Use cross joins.
SELECT PRODUCT_NAME, QUANTITY_ON_HAND, WAREHOUSE_NAME
FROM WAREHOUSES
NATURAL JOIN INVENTORIES
NATURAL JOIN PRODUCT_INFORMATION
ORDER BY PRODUCT_NAME;
Now I don't know what to do. For me it doesn't make sense to replace natural join by cross join or isn't even possible?!
Please help.
Diagram:
The cross join can be seen also as a cartesian product: so every row of the first table is combined with a row on the second one, so the resulting number of rows will be rows(TableA) * rows(TableB).
To emulate a natural join with a cross join you'll need to compare the foreign/primary key of the different tables to see if they are the same like this:
SELECT PRODUCT_NAME, QUANTITY_ON_HAND, WAREHOUSE_NAME
FROM WAREHOUSES
CROSS JOIN INVENTORIES
CROSS JOIN PRODUCT_INFORMATION
WHERE WAREHOUSES.WAREHOUSES_ID = INVENTORIES.WAREHOUSE_ID AND
INVENTORIES.PRODUCT_ID = PRODUCT_INFORMATION.PRODUCT_ID
ORDER BY PRODUCT_NAME;
If you need more information about cross-join or natural join.
If it can help you try to think at it like this:
First you create a table with all the possible combination of rows
between the three tables
Than you start compare on each row the common and repetitive field, you've on each row 2 PRODUCT_ID and WAREHOUSE_ID columns, each of them coming from his specific table (try to execute the query taking all the columns with * to see this).
After that you take only the rows where the 2 type of columns have the same value (Emulating a natural join)
You're just doing a normal join....with extra steps.

SQL Server View tables not joining

I am incredibly new to SQL and am trying to create a view for a pizza store database. The sides ordered table and the sides names table have to be separate but need a view that combines them.
This is the code I have entered,
CREATE VIEW ordered_sides_view
AS
SELECT
ordered_side_id, side.side_id, side_name, number_ordered,
SUM(number_ordered * price) AS 'total_cost'
FROM
ordered_side
FULL JOIN
side ON ordered_side.side_id = side.side_id
GROUP BY
ordered_side_id, side.side_id, side_name, number_ordered;
The problem is that this is the resulting table.
Screenshot of view table:
How do I get the names to match the ordered sides?
You fail to understand what a FULL JOIN and an INNER JOIN operation does.
FULL JOIN returns at least every row from each table (plus any extra values from the ON clause).
INNER JOIN returns only matching row sets based on the ON clause.
OUTER JOIN returns every matching row set PLUS the side of the join that the OUTER JOIN is on (LEFT OUTER JOIN vs RIGHT OUTER JOIN).
In your picture, you can clearly see that there are no rows that match from the tables ordered_side and side...
That is why switching to an INNER JOIN returns zero rows...there are no matches on the COLUMNS YOU CHOSE TO USE.
Why in your SELECT operator do you have this:
SELECT ordered_side_id, side.side_id, side_name, number_ordered,
while your ON clause has this:
side ON ordered_side.side_id = side.side_id
ordered_side_id !=ordered_side.side_id
Investigate your columns and fix your JOIN clause to match the correct columns.
P.S. I like how you structure your queries. Very nice and what an
expert does! It makes reading MUCH, MUCH easier. :)
One suggestion I might add is structure your columns in the SELECT statement in its own row:
SELECT ordered_side_id
, side.side_id
, side_name
, number_ordered
, SUM(number_ordered * price) AS Total_Cost --or written [Total_Cost]/'Total_Cost'
FROM ordered_side
FULL JOIN side ON ordered_side.ordered_side_id = side.side_id
GROUP BY ordered_side_id
, side.side_id
, side_name
, number_ordered;

Can I do a left join without returning the conditional columns?

New to SQL but I want to be able to optimize my query by bringing just the right amount of data. I am doing a left join on CS Rep Name and WE, which are two columns present in both tables. I find that if I don't bring in CS Rep Name and WE in the TECDR table, the query would error. Is there a workaround to this? Since it is a left join, I don't need redundant data.
SELECT *
FROM Tish_Email_CSAT_Dump AS TECD
LEFT JOIN (SELECT CS_Rep_Name,
Team_Leader,
Operations_Manager,
Tenure,
WE,
FileName
FROM Tish_Email_CSAT_Dump_Roster) AS TECDR
ON TECD.CS_Rep_Name = TECDR.CS_Rep_Name
AND TECD.WE = TECDR.WE
When you embed a SELECT inside a query in place of a table, the result of a select (projection) behave like a table visible only inside the query.
In your case, the join is the same as if there were a table called TECDR with the columns that you select. Hence, if you leave out some columns of Tish_Email_CSAT_Dump_Roster from your SELECT, these columns would not be available for joining or selection.
However, in your case this is unnecessary: all you need to do is joining to the underlying table, like this:
SELECT
TECD.*
, TECDR.Team_Leader
, TECDR.Operations_Manager
, TECDR.Tenure
, TECDR.FileName
FROM Tish_Email_CSAT_Dump AS TECD
LEFT JOIN Tish_Email_CSAT_Dump_Roster AS TECDR
ON TECD.CS_Rep_Name = TECDR.CS_Rep_Name AND TECD.WE = TECDR.WE
select
<place the columns you want here>
from
Tish_Email_CSAT_Dump as TECD
Left join Tish_Email_CSAT_Dump_Roster as TECDR
On TECD.CS_Rep_Name = TECDR.CS_Rep_Name and TECD.WE = TECDR.WE
Hope the following helps or else please share the query that errors:
select TECD.Column1, TECD.Column2, TECDR.Column1, TECDR.Column2
from Tish_Email_CSAT_Dump as TECD
Left join Tish_Email_CSAT_Dump_Roster as TECDR
On TECD.CS_Rep_Name = TECDR.CS_Rep_Name and TECD.WE = TECDR.WE

SQLite query select all records that does not exist in another table

I am having some problem when trying to perform a SQLite query to get the records which does not exist from another table. Basically I have two database tables:
My exercise table stored all the exercises available whereas the bookedExercise table store the exercises booked by each users. What I am trying to do is, for example if the exercise does exist in the bookedExercise, it should be filtered out.
Here is the SQLite query which I used:
SELECT exercise.exerciseID, exercise.exerciseType, exercise.amout FROM exercise LEFT JOIN bookedExercise WHERE exercise.exerciseID = bookedExercise.exerciseID AND bookedExercise.exerciseID IS NULL
However, it returned me empty records. Any ideas?
Thanks in advance.
If you're fine with not using joins you could use
SELECT * FROM exercise WHERE exerciseID not in (SELECT exerciseID FROM bookedExercise)
When you are using LEFT JOIN, you must put the join condition into the ON clause:
SELECT exercise.exerciseID,
exercise.exerciseType,
exercise.amout
FROM exercise /* !! */
LEFT JOIN bookedExercise ON exercise.exerciseID = bookedExercise.exerciseID
WHERE bookedExercise.exerciseID IS NULL
Your SQL looked okay... I think the problem might be you have a datatype mismatch. You have exercise ID as an integer in one table and text in another.
Also, if you have huge data volumes, you may want to consider an anti-join:
select
e.*
from
exercise e
where not exists (
select 1
from bookedExercise be
where
e.excerciseId = be.exerciseID
)
-- edit --
On second glance, your SQL was not okay. You had your join condition in the where clause. This little change would fix your existing SQL:
SELECT exercise.excerciseId , exercise.exerciseType , exercise.amout
FROM exercise LEFT JOIN bookedExercise on
exercise.excerciseId = bookedExercise.exerciseID
WHERE bookedExercise.exerciseID IS NULL

multiple sql joins not producing desired results

I'm new to sql and trying to tweak someone else's huge stored procedure to get a subset of the results. The code below is maybe 10% of the whole procedure. I added the lp.posting_date, last left join, and the where clause. Trying to get records where the posting date is between the start date and the end date. Am I doing this right? Apparently not because the results are unaffected by the change. UPDATE: I CHANGED THE LAST JOIN. The results are correct if there's only one area allocation term. If there is more than one area allocation term, the results are duplicated for each term.
SELECT Distinct
l.lease_id ,
l.property_id as property_id,
l.lease_number as LeaseNumber,
l.name as LeaseName,
lty.name as LeaseType,
lst.name as LeaseStatus,
l.possession_date as PossessionDate,
l.rent as RentCommencementDate,
l.store_open_date as StoreOpenDate,
msr.description as MeasureUnit,
l.comments as Comments ,
lat.start_date as atStartDate,
lat.end_date as atEndDate,
lat.rentable_area as Rentable,
lat.usable_area as Usable,
laat.start_date as aatStartDate,
laat.end_date as aatEndDate,
MK.Path as OrgPath,
CAST(laa.percentage as numeric(9,2)) as Percentage,
laa.rentable_area as aaRentable,
laa.usable_area as aaUsable,
laa.headcounts as Headcount,
laa.area_allocation_term_id,
lat.area_term_id,
laa.area_allocation_id,
lp.posting_date
INTO #LEASES FROM la_tbl_lease l
INNER JOIN #LEASEID on l.lease_id=#LEASEID.lease_id
INNER JOIN la_tbl_lease_term lt on lt.lease_id=l.lease_id and lt.IsDeleted=0
LEFT JOIN la_tlu_lease_type lty on lty.lease_type_id=l.lease_type_id and lty.IsDeleted=0
LEFT JOIN la_tlu_lease_status lst on lst.status_id= l.status_id
LEFT JOIN la_tbl_area_group lag on lag.lease_id=l.lease_id
LEFT JOIN fnd_tlu_unit_measure msr on msr.unit_measure_key=lag.unit_measure_key
LEFT JOIN la_tbl_area_term lat on lat.lease_id=l.lease_id and lat.isDeleted=0
LEFT JOIN la_tbl_area_allocat_term laat on laat.area_term_id=lat.area_term_id and laat.isDeleted=0
LEFT JOIN dbo.la_tbl_area_allocation laa on laa.area_allocation_term_id=laat.area_allocation_term_id and laa.isDeleted=0
LEFT JOIN vw_FND_TLU_Menu_Key MK on menu_type_id_key=2 and isActive=1 and id=laa.menu_id_key
INNER JOIN la_tbl_lease_projection lp on lp.lease_projection_id = #LEASEID.lease_projection_id
where lp.posting_date <= laat.end_date and lp.posting_date >= laat.start_date
As may have already been hinted at you should be careful when using the WHERE clause with an OUTER JOIN.
The idea of the OUTER JOIN is to optionally join that table and provide access to the columns.
The JOINS will generate your set and then the WHERE clause will run to restrict your set. If you are using a condition in the WHERE clause that says one of the columns in your outer joined table must exist / equal a value then by the nature of your query you are no longer doing a LEFT JOIN since you are only retrieving rows where that join occurs.
Shorten it and copy it out as a new query in ssms or whatever you are using for testing. Use an inner join unless you want to preserve the left side set even when there is no matching lp.lease_id. Try something like
if object_id('tempdb..#leases) is not null
drop table #leases;
select distinct
l.lease_id
,l.property_id as property_id
,lp.posting_date
into #leases
from la_tbl_lease as l
inner join la_tbl_lease_projection as lp on lp.lease_id = l.lease_id
where lp.posting_date <= laat.end_date and lp.posting_date >= laat.start_date
select * from #leases
drop table #leases
If this gets what you want then you can work from there and add the other left joins to the query (getting rid of the select * and 'drop table' if you copy it back into your proc). If it doesn't then look at your Boolean date logic or provide more detail for us. If you are new to sql and its procedural extensions, try using the object explorer to examine the properties of the columns you are querying, and try selecting the top 1000 * from the tables you are using to get a feel for what the data looks like when building queries. -Mike
You can try the BETWEEN operator as well
Where lp.posting_date BETWEEN laat.start_date AND laat.end_date
Reasoning: You can have issues wheres there is no matching values in a table. In that instance on a left join the table will populate with null. Using the 'BETWEEN' operator insures that all returns have a value that is between the range and no nulls can slip in.
As it turns out, the problem was easier to solve and it was in a different place in the stored procedure. All I had to do was add one line to one of the cursors to include area term allocations by date.