SQL join 4 tables with WHERE query - sql

I am trying to join 4 tables together as shown in this diagram here:
https://imgur.com/a/jukJvSw
The SQL query I have written returns all fields except TExpiryDate and I have not come across any examples online that can help me understand this. Please help.
SELECT tbPurchaseHeader.PurchaseDate,
tbSupplier.CompanyName,
tbPurchaseDetails.UnitCost,
tbPurchaseDetails.Quantity,
tbPurchaseDetails.Bonus,
tbpurchasedetails.BatchID,
tbBatch.TExpiryDate
FROM ((tbPurchaseDetails
INNER JOIN tbPurchaseHeader
ON tbPurchaseDetails.PurchaseID = tbPurchaseHeader.PurchaseID)
LEFT JOIN tbBatch
ON tbPurchaseDetails.BID = tbBatch.BID)
INNER JOIN tbSupplier
ON tbPurchaseHeader.SupplierID = tbSupplier.SupplierID
WHERE tbPurchaseDetails.ProductID = ?
ORDER BY tbPurchaseHeader.PurchaseDate

Turns out BID contains empty values in the database. I have decided to make links elsewhere to get the data. Thanks everyone for making me realise this.

Related

SQL Query for Reporting

I am trying to join two tables and getting the data for my report. Is there any best way to get the details as per below report?
I have tried below query and getting the results. Please find my query.
SELECT wl.trasaction_id
,wl.supplier_id
,wl.sp_patientpid
,wl.dm_id AS original_dm_id
,NVL(cr.new_dm_id,wl.dm_id) AS out_dm_id
FROM weekly_load wl
LEFT JOIN cross_ref cr
ON wl.sp_patientpid = cr.sp_patient_id
AND wl.supplier_id = cr.ims_supplier_id
Kindly help me.
Many thanks.
You may need an additional join condition on the dm ids:
SELECT wl.trasaction_id, wl.supplier_id, wl.sp_patientpid, wl.dm_id AS original_dm_id,
COALESCE(cr.new_dm_id, wl.dm_id) AS out_dm_id
FROM weekly_load wl LEFT JOIN
cross_ref cr
ON wl.sp_patientpid = cr.sp_patient_id AND
wl.supplier_id = cr.ims_supplier_id AND
wl.dm_id = cr.old_dm_id;

MS Access 2016 Error: "Multi-level group by not allowed"

i'm stuck at another point in my little Access 2016 Database. My code looks like the following and i know it probably isn't the cleanest solution but i'm kinda new to this and i tried to educate myself and get some help here already.
I'm trying to play around with the reports now a little bit and i am using this test query which returns all entries of two tables joined together.
As far as i could find out I have this one subquery included that returns the prvious day inventory for each record and that is most likely the cause of my error. I found a possible solution with adding SELECT * FROM at the beginning of my code but i get a Syntax error when i do that and i'm not sure how to solve this problem.
here's my code
SELECT Stations.StationName, Product.ProductName, GasInventoryTransactions.TransactionDate, (SELECT TOP 1 Dupe.ActualInventory FROM GasInventory AS Dupe WHERE Dupe.StationID = Stations.StationID AND Dupe.ProductID = Product.ProductID AND Dupe.InventoryDate < GasInventory.InventoryDate ORDER BY Dupe.InventoryDate DESC) AS PreviousDayInventory, GasInventory.ActualInventory, GasInventoryTransactions.GasSales, GasInventoryTransactions.GasDelivery, [PreviousDayInventory]+[GasDelivery]-[GasSales] AS BookBalance, GasInventory.ActualInventory, [ActualInventory]-[BookBalance] AS OverShort
FROM (Stations INNER JOIN (Product INNER JOIN GasInventory ON Product.[ProductID] = GasInventory.[ProductID]) ON Stations.[StationID] = GasInventory.[StationID]) INNER JOIN GasInventoryTransactions ON GasInventory.[InventoryDate] = GasInventoryTransactions.[TransactionDate];
thanks for your help!

Access SQL query without duplicate results

I made a query and wanted to not have any duplicates but i got some times 3 duplicates and when i used DISTINCT or DISTINCTROW i got only 2 duplicates.
SELECT f.flight_code,
f.status,
a.airport_name,
a1.airport_name,
f.departing_date+f.departing_time AS SupposedDepartingTime,
f.landing_date+f.landing_time AS SupposedLandingTime,
de.actual_takeoff_date+de.actual_takeoff_time AS ActualDepartingTime,
SupposedLandingTime+(ActualDepartingTime-SupposedDepartingTime) AS ActualLandingTime
FROM
(((Flights AS f
LEFT JOIN Aireports AS a
ON a.airport_code = f.depart_ap)
LEFT JOIN Aireports AS a1
ON f.target_ap = a1.airport_code)
LEFT JOIN Irregular_Events AS ie
ON f.flight_code = ie.flight_code)
LEFT JOIN Delay_Event AS de
ON ie.IE_code = de.delay_code;
had to use LEFT JOIN because when i used INNER JOIN i missed some of the things i wanted to show because i wanted to see all the flights and not only the flights that got delayed or canceled.
This is the results when i used INNER JOIN, you can see only the flights that have the status "ביטול" or "עיכוב" and that is not what i wanted.
[the results with LEFT JOIN][2]
[2]: https://i.stack.imgur.com/cgE2G.png
and when i used DISTINCT where you see the rows with the NUMBER 6 on the first column it appear only two times
IMPORTANT!
I just checked my query and all the tables i use there and i saw my problem but dont know how to fix it!
in the table Irregular_Events i have more the one event for flights 3,6 and 8 and that is why when i use LEFT JOIN i see more even thou i use distinct, please give me some help!
Not entirely sure without seeing the table structure, but this might work:
SELECT f.flight_code,
f.status,
a.airport_name,
a1.airport_name,
f.departing_date+f.departing_time AS SupposedDepartingTime,
f.landing_date+f.landing_time AS SupposedLandingTime,
de.actual_takeoff_date+de.actual_takeoff_time AS ActualDepartingTime,
SupposedLandingTime+(ActualDepartingTime-SupposedDepartingTime) AS ActualLandingTime
FROM
((Flights AS f
LEFT JOIN Aireports AS a
ON a.airport_code = f.depart_ap)
LEFT JOIN Aireports AS a1
ON f.target_ap = a1.airport_code)
LEFT JOIN
(
SELECT
ie.flight_code,
de1.actual_takeoff_date,
de1.actual_takeoff_time
FROM
Irregular_Events ie
INNER JOIN Event AS de1
ON ie.IE_code = de1.delay_code
) AS de
ON f.flight_code = de.flight_code
It is hard to tell what is the problem with your query without any sample of the output, and without any description of the structure of your tables.
But your problem is that your are querying from the flights table, which [I assume] can be linked to multiple irregular_events, which can possibly also be linked to multiple delay_event.
If you want to get only one row per flight, you need to make sure your joins return only one row too. Maybe you can do it by adding one more condition to the join, or by adding a condition in a sub-query.
EDIT
You could try to add a GROUP BY to the query:
GROUP BY
f.flight_code,
f.status,
a.airport_name,
a1.airport_name;

SQL Joins are not working properly

I am new to JOINS and testing my query, but it's just not working for me...
The situation:
The database has got the following columns:
links (contains unique data)
cl_link (contains the relation between links & cats)
cats (cat. descriptions
images (contains multiple images of one link)
cfvalues (contains the values of the multiple custom fiels
customfields (contains the multiple customfields)
I am using the following query, but the Joins are not working for me. Because I only get one image while sometimes there are multiple. And I only get one customfield instead of multiple and I get none cfvalues.
I guess something is wrong with the JOINS, but I am not sure. Can somebody help me out here?
The SQL
SELECT DISTINCT
rqypj_mt_links.link_name,
rqypj_mt_links.link_desc,
rqypj_mt_links.address,
rqypj_mt_links.city,
rqypj_mt_links.state,
rqypj_mt_links.country,
rqypj_mt_links.postcode,
rqypj_mt_links.telephone,
rqypj_mt_links.fax,
rqypj_mt_links.email,
rqypj_mt_links.website,
rqypj_mt_links.price,
rqypj_mt_links.lat,
rqypj_mt_links.lng,
rqypj_mt_links.zoom,
rqypj_mt_cats.cat_name,
rqypj_mt_images.filename,
rqypj_mt_cfvalues.value,
rqypj_mt_customfields.caption
FROM rqypj_mt_links
LEFT JOIN rqypj_mt_cl
ON rqypj_mt_links.link_id = rqypj_mt_cl.link_id
LEFT JOIN rqypj_mt_cats
ON rqypj_mt_cl.cat_id = rqypj_mt_cats.cat_id
LEFT JOIN rqypj_mt_images
ON rqypj_mt_links.link_id = rqypj_mt_images.link_id
LEFT JOIN rqypj_mt_cfvalues
ON rqypj_mt_links.link_id = rqypj_mt_cfvalues.link_id
LEFT JOIN rqypj_mt_customfields
ON rqypj_mt_customfields.cf_id = rqypj_mt_customfields.cf_id LIMIT 100
Thanks in advance!
Jelte
your last condition doesn't look right:
on rqypj_mt_customfields.cf_id = rqypj_mt_customfields.cf_id
translates to 1=1
Shouldn't it be:
on rqypj_mt_customfields.cf_id = rqypj_mt_cfvalues.cf_id
Probably because you don't have an order by and are using limit.
Change it to
order by rqypj_mt_links.link_id, rqypj_mt_cl.cat_id
limit 100
and then your multiple pictures for the same link should be together.
Also please consider use of alias to make your code easier to read:
SELECT DISTINCT
links.link_name,
links.link_desc,
links.address,
links.city,
links.state,
links.country,
links.postcode,
links.telephone,
links.fax,
links.email,
links.website,
links.price,
links.lat,
links.lng,
links.zoom,
cats.cat_name,
images.filename,
cfvalues.value,
--custom.caption
FROM rqypj_mt_links links
LEFT JOIN rqypj_mt_cl cl ON links.link_id = cl.link_id
LEFT JOIN rqypj_mt_cats cats ON cl.cat_id = cats.cat_id
LEFT JOIN rqypj_mt_images images ON links.link_id = images.link_id
LEFT JOIN rqypj_mt_cfvalues cfvalues ON links.link_id = cfvalues.link_id
--LEFT JOIN rqypj_mt_customfields custom ON custom.cf_id = custom.cf_id
ORDER BY links.link_id, cats.cat_id
LIMIT 100

relationships produce duplicate records on query, DISTINCT does not work, any other solutions available?

I am new to this portal. I have a very simple problem to be solved. It is related to the ANSI SQL. I am writing a reports using BIRT and I am fetching the data from several tables. I understand how the SQL joins work but maybe not fully. I researched google for hours and I could not find relevant answer.
My problem is that one of the relationships in the code produce a duplicate result (the same row is copied - duplicated). I was so determined to solve it I used every type of join available. Some of this SQL was produced already. I shall post my code below. I know that one of the solutions to my problem is use of the 'DISTINCT' keyword. I have used it and it does not solve my problem.
Can anyone propose any solution to that?
Sample code:
SELECT DISTINCT
partmaster.partdesc,
partmaster.uom,
traders.name AS tradername,
worksorders.id AS worksorderno,
worksorders.partid,
worksorders.quantity,
worksorders.duedate,
worksorders.traderid,
worksorders.orderid,
routingoperations.partid,
routingoperations.methodid,
routingoperations.operationnumber,
routingoperations.workcentreid,
routingoperations.settime,
routingoperations.runtime,
routingoperations.perquantity,
routingoperations.description,
routingoperations.alternativeoperation,
routingoperations.alternativeoperationpreference,
machines.macdesc,
machines.msection,
allpartmaster.partnum,
allpartmaster.nbq,
allpartmaster.partdesc,
routingoperationtools.toolid,
tools.tooldesc,
CAST (emediadetails.data as VARCHAR(MAX)) AS cplandata
FROM worksorders
INNER JOIN partmaster ON worksorders.partid = partmaster.partnum
INNER JOIN traders traders ON worksorders.traderid = traders.id
INNER JOIN routingoperations routingoperations ON worksorders.partid = routingoperations.partid
AND worksorders.routingmethod = routingoperations.methodid
INNER JOIN allpartmaster allpartmaster ON routingoperations.partid = allpartmaster.partnum
LEFT OUTER JOIN machines machines ON routingoperations.workcentreid = machines.macid
LEFT OUTER JOIN routingoperationtools routingoperationtools ON routingoperationtools.partid = routingoperations.partid
AND routingoperationtools.routingmethod = routingoperations.methodid
AND routingoperationtools.operationnumber = routingoperations.operationnumber
LEFT OUTER JOIN tools tools ON tools.toolid = routingoperationtools.toolid
LEFT OUTER JOIN emediadetails ON emediadetails.keyvalue1 = worksorders.id
AND emediadetails.keyvalue2 = routingoperations.operationnumber
AND emediadetails.emediaid = 'worksorderoperation'
I do not have too much of the test data but I know that one row is copied twice as the result of the query below even tho I used DISTINCT keyword. I know that my problem is rather specific and not general but the solution that someone will propose may help others with the similar problem.
I can't solve your problem for you without some test data, but I have some helpful hints.
In principle, you should be really careful with DISTINCT - its a great way of hiding bugs in your query. Only use DISTINCT if you are confident that the underlying data contains legitimate duplicates. If your joins are wrong, and you're getting a cartesian product, you can remove the duplicates from the results with DISTINCT - but that doesn't stop the cartesian product being generated. You'll get very poor performance, and possibly incorrect data.
Secondly, I am pretty sure that DISTINCT works properly - you are almost certainly not getting duplicates, but it may be hard to spot the difference between two rows. Leading or trailing spaces in text columns, for instance could be to blame.
Finally, to work through this problem, I'd recommend building the query up join by join, and seeing where you get the duplicate - that's the join that's to blame.
So, start with:
SELECT
traders.name AS tradername,
worksorders.id AS worksorderno,
worksorders.partid,
worksorders.quantity,
worksorders.duedate,
worksorders.traderid,
worksorders.orderid
FROM worksorders
INNER JOIN traders traders ON
worksorders.traderid = traders.id
and build up to the next join.
Are you sure the results are exact duplicates? Makes sure there isn't one column that actually has a different value.