SQL Server : join tables causes the data to duplicate on every row - sql

I have this query which is returning some redundant data. Can somebody please help me to correct this query. I have also attached the table relationship.
SELECT
dbo.supplierOrder.sectionID,
dbo.supplierOrder.supplierID,
dbo.supplierOrder.supplierOrderNo,
dbo.supplierOrder.supplierOrderCreated,
dbo.supplierOrder.supplierOrderConfirmStatus,
dbo.supplierOrderDetails.productID,
dbo.supplierOrderDetails.orderQty,
dbo.supplierOrderReceive.invoiceno,
dbo.supplierOrderReceive.supplierInvoiceno,
dbo.supplierOrderReceive.ID,
dbo.supplierOrderReceiveDetail.qtyArrived
FROM
dbo.supplierOrder
INNER JOIN
dbo.supplierOrderDetails ON (dbo.supplierOrderDetails.supplierOrderID = dbo.supplierOrder.ID)
INNER JOIN
dbo.supplierOrderReceive ON (dbo.supplierOrderReceive.supplierOrderID = dbo.supplierOrder.ID)
INNER JOIN
dbo.supplierOrderReceiveDetail ON (dbo.supplierOrderReceiveDetail.supplierOrderReceiveID = dbo.supplierOrderReceive.ID)
WHERE
dbo.supplierOrder.ID = 1 ;
here is the output that I get
which is not exactly what I was want. the last column qtyArrived should show only its related qty but here as you can see it is repeating for each of the productID
and here is the db tables and relationship

I think the last table should be join using also ProductId not only OrderID :
LEFT JOIN
dbo.supplierOrderReceiveDetail
ON
(dbo.supplierOrderReceiveDetail.supplierOrderReceiveID=dbo.supplierOrderReceive.ID)
AND
(dbo.supplierOrderReceiveDetail.ProductID =dbo.sdbo.supplierOrderDetails.ProductID)

Related

Getting repeats of output, possibly doing a join wrong?

I'm having an issue where I'm getting some incorrect values in my output. I am binding the below highlighted table column with the circled column down the bottom. The service_id on the highlighted column is what is unique, but I need to bind the booking_id to retrieve the info (if that makes sense. What I end up getting is the top table where I get repeats, or the price is wrong. I should be getting only 5 lines in the top table.
Here's my code. I suspect I might be doing the join wrong?
SELECT bad.agent as Agents,
dog.SUPPLIER as SUPPLIER,
bad.status as TheStatus,
country.analysis_master1 as Country,
ftb.booking_actual_retail as BookingActualRetail,
ftb.Booking_Actual_Cost as BookingCost,
ftb.Booking_Actual_Retail_inc as BookingRetailINC,
fts.Service_Id,
fts.Service_Actual_Retail_inc as ServiceActualCostInc,
Product.SERVICE,
Product.SL_STATUS as SLSTATUS,
cat.name as Product2,
bad.LAST_SERVICE_DATE as Servicedate,
bad.LW_DATE as LWDATE,
ftb.Entered_Date as DATEENTERED,
ftb.Booking_Pax as PEOPLE,
ftb.Booking_Children as KIDS,
bad.TRAVELDATE as TRAVELDATE,
bad.FULL_REFERENCE
from BHD bad
inner join FTB on bad.FULL_REFERENCE = ftb.booking_reference
inner join FTS on FTB.Booking_Id = fts.Booking_Id
inner join DRM Country on bad.agent = country.code
inner join BSL Product on bad.BHD_ID = Product.BHD_ID
inner join SRV cat on Product.SERVICE = cat.CODE
inner join OPT dog on Product.OPT_ID = dog.OPT_ID
where bad.STATUS = 'IV' AND bad.FULL_REFERENCE = 'LTIT129488'
UPDATE:
Ok, so it looks like this join here causes the multiple outputs:
inner join FTS on FTB.Booking_Id = fts.Booking_Id
I have included the two tables, their headers, and sample data
You have somewhere put the join for the service or supplier in the wrong way.. Please check this line again.
inner join SRV cat on Product.SERVICE = cat.CODE
UPDATED SOLUTION :
As per your updated screenshots, I found the issue...
you have joined like this.
inner join FTB on bad.FULL_REFERENCE = ftb.booking_reference
In this join, your one table has single record against booking reference while another have multiple records against booking refrence. Thats why you are getting the multiple records in the output.
Remove this join and your problem will be solved. If you really want the data from this table then you can select in other way like using outer apply etc.

Parent child relationship Join tables in oracle sql

I have a requirement below.
Now I have to get output like below
How can this be achieved ?
I have written the below SQL but parent_position_id is coming, not parent_position_code
select
hapf.position_code,
pphf.parent_position_id
from
hr_all_positions_f hapf, PER_POSITION_HIERARCHY_F pphf
where
hapf.position_id = pphf.position_id
Should I write a sub query? How should I proceed ?
This is Oracle SQL
Thanks,
Shivam
Noone ever said you could only join a table in once:
select
chi.position_code,
par.position_code as parent_position_code
from
hr_all_positions_f hapf
INNER JOIN PER_POSITION_HIERARCHY_F chi on hapf.position_id = chi.position_id
INNER JOIN PER_POSITION_HIERARCHY_F par on hapf.parent_position_id = par.position_id
Bear it in mind; I see people coming to thinking all the time that they can only join a table once. If one table decodes a value in 3 different columns, then you sure can join that same table in 3 times... Imagine if it were an address table, and a Student had a HomeAddressId, WorkAddressId and StudyAddressId, and the Address table held all these addresses - you'd join the addresses table to the Student table 3 times to get all the data..

SQL: If there is No match on condition (row in table) return a default value and Rows which match from different tables

I have three tables: Clinic, Stock and StockLog.
I need to get all rows where Stock.stock < 5. I need to also show if an order has been placed and what amount it is; which is found in the table Stocklog.
The issue is that a user can set his stock level in the Stock table without placing an order which would go to Stocklog.
I need a query that can : return the rows in the Stock table and get the related order amounts in the Stocklog table. If no order has been placed in StockLog, then set amount to order amount to zero.
I have tried :
SELECT
Clinic.Name,
Stock.NameOfMedication, Stock.Stock,
StockLog.OrderAmount
FROM
Clinic
JOIN
Stock ON Stock.ClinicID = Clinic.ClinicID
JOIN
StockLog ON StockLog.StockID = Stock.StockID
WHERE
Stock.Stock <= 5
The issue with my query is that I lose rows which are not found in StockLog.
Any help on how to write this.
Thank you.
I am thinking the query should look like this:
SELECT c.Name, s.NameOfMedication, s.Stock,
COALESCE(sl.OrderAmount, 0) as OrderAmount
FROM Stock s LEFT JOIN
Clinic c
ON s.ClinicID = c.ClinicID LEFT JOIN
StockLog sl
ON sl.StockID = s.StockID
WHERE s.Stock <= 5 ;
You want to keep all rows in Stock (subject to the WHERE condition). So think: "make Stock the first table in the FROM and use LEFT JOIN for all the other tables."
If you want to keep all the rows that result from joining Clinic and Stock, then use a LEFT OUTER JOIN with StockLog. I don't know which SQL you're using (SQL Server, MySQL, PostgreSQL, Oracle), so I can't give you a precise example, but searching for "left outer join" in the relevant documentation should work.
See this Stack Overflow post for an explanation of the various kinds of joins.

Self Join with on different tables

I wrote the following query:
SELECT R1.RELATIONSHIP_ID, R1.SUPPLIER_ACCOUNT_ID, R2.BUYER_ACCOUNT_ID
FROM RELATIONSHIP R1 JOIN RELATIONSHIP R2
ON (R1.RELATIONSHIP_ID = R2.RELATIONSHIP_ID)
ORDER BY SUPPLIER_ACCOUNT_ID;
For the tables:
1. RELATIONSHIP: Columns: RELATIONSHIP_ID, SUPPLIER_ACCOUNT_ID, BUYER_ACCOUNT_ID ...
2. ACCOUNT: ACCOUNT_ID, XX_ACCOUNT_ID ....
and gives the result correctly so far
However, what I want is more complicated. I need to replace the second and third columns with a column called XX_ACOUNT_ID to be shown twice. Each SUPPLIER_ACCOUNT_ID and BUYER_ACCOUNT_ID has a unique XX_ACCOUNT_ID and a unique ACCOUNT_ID. XX_ACCOUNT_ID belongs to the table ACCOUNTS in which there is ACCOUNT_ID (SUUPLIER_ACCOUNT_ID & BUYER_ACCONT_ID are referenced from this column) and XX_ACCOUNT_ID. I'm a bit confused that does it need nested self-join or multiple inner joins? or subqueries to solve this?
If R1.Supplier_Account_ID and R2.Buyer_Account_ID will always exist in the referenced tables, multiple inner joins should work. Try something like this:
SELECT R1.RELATIONSHIP_ID, AcctSupp.XX_ACOUNT_ID, AcctBuyer.XX_ACOUNT_ID
FROM RELATIONSHIP R1
JOIN RELATIONSHIP R2 ON (R1.RELATIONSHIP_ID = R2.RELATIONSHIP_ID)
JOIN Accounts AcctSupp ON R1.SUPPLIER_ACCOUNT_ID = AcctSupp.Account_ID
JOIN Accounts AcctBuyer ON R2.BUYER_ACCOUNT_ID = AcctBuyer.Account_ID
ORDER BY SUPPLIER_ACCOUNT_ID;
If there's any chance the values won't exist in the referenced tables, use left joins instead:
SELECT R1.RELATIONSHIP_ID, AcctSupp.XX_ACOUNT_ID, AcctBuyer.XX_ACOUNT_ID
FROM RELATIONSHIP R1
JOIN RELATIONSHIP R2 ON (R1.RELATIONSHIP_ID = R2.RELATIONSHIP_ID)
LEFT JOIN Accounts AcctSupp ON R1.SUPPLIER_ACCOUNT_ID = AcctSupp.Account_ID
LEFT JOIN Accounts AcctBuyer ON R2.BUYER_ACCOUNT_ID = AcctBuyer.Account_ID
ORDER BY SUPPLIER_ACCOUNT_ID;
Perhaps I misunderstood the question, but I don't see why you need a self join:
SELECT R.Relationship_Id,
Supplier.xx_account_id sup_id,
Buyer.xx._account_id buy_id
FROM Relationship AS R
JOIN Accounts AS Buyer
ON R.Buyer_account_Id = Buyer.Account_Id
JOIN Accounts AS Supplier
ON R.Supplier_account_Id = Supplier.Account_Id

SQL like clause is not returning any results

I have following query, but it doesn't return any results for where clauses, even when there is row with that kind of name what is queried. If I remove where clause, then all records in Company table which have OfficeLocation table are returned. What is wrong in my query?
SELECT c.*
FROM [MyDb].[dbo].[Company] AS c
INNER JOIN [MyDb].[dbo].[CompanyOfficeLocation] AS col ON c.Id = col.CompanyId
INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON ol.Id = col.OfficeLocationId
WHERE ol.Name like '%Actual Name In This Table%';
Table structure :
Company
Id
etc ...
CompanyOfficeLocation
CompanyId
OfficeLocationId
OfficeLocation
Id
etc ...
Two things for a record to show up given your query:
The OfficeLocation you specified (given the ol.Name value) must have an Id value that is used by a record in the CompanyOfficeLocation table in its OfficeLocationId.
The CompanyOfficeLocation record that you got in #1 must have a CompanyId that exists in the Company table.
If any of those two criteria are not met, then no records will show up in your query result. The INNER JOIN is essentially an 'AND' clause. If a record could not be related to at least one INNER JOINed table, then that record will not show up at all.
If you want a record to show up despite not having any related records in the joined tables, you may want to consider using OUTER JOINs. A RIGHT JOIN in your case to be exact.
I do not find any mistake however I'd suggest you switch the columns after ON when joining to maintain standards.
Instead of - INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON ol.Id = col.OfficeLocationId
Do - INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON col.OfficeLocationId = ol.Id