I like to create a table which can show parts ID, parts name and its most recent supplier's name. These information are separated in 3 tables - BOM table(Field Name=>drawingN, partsID, partsName), purchase_history table (partsID, supplierID, purchaseDate) and supplier_list table(supplierID, supplierName).
In BOM table, parts are categorize by drawing number, so I use following SQL to get parts ID that I want:
SELECT drawingN, partsID, partsName
FROM BOM
WHERE drawingN = 'I16253'
In purchase_history, because the same parts may purchased from different supplier over time, so I use following SQL to screen out the most recent one. I also LEFT JOIN supplier_list to make supplier name shown in the table. In addition, supplierID 2991 and 2992 means oders that had been canceled or modified, so I what to rule them out too.
SELECT TOP 1 purchase_history.partsID, supplier_list.supplierName
FROM purchase_history
LEFT JOIN supplier_list ON purchase_history.supplierID = supplier_list.supplierID
WHERE partsID = 'A1234' AND supplierID <> '2991' AND supplierID <> '2992'
ORDER BY purchaseDate DESC
From first SQL query, database returns:
drawingN | partsID | partsName |
---|---|---|
I16253 | A1234 | Bolts |
I16253 | B5678 | Spring |
From second SQL query, database returns:
partsID | supplierName |
---|---|
A1234 | ABC Company |
Is it possible to combine first and second SQL to make database returns something like this:
drawingN | partsID | partsName | supplierName |
---|---|---|---|
I16253 | A1234 | Bolts | ABC Company |
I16253 | B5678 | Spring | DEF Company |
Now I just keep chaning partsID = 'A1234' to partsID = 'B5678' in second SQL to get B5678's company name. I tried subquery, but it doesn't go right. Thanks for the help.
2条答案
按热度按时间8ljdwjyq1#
Seems like it should be:
I tried to work out what made the most sense based on the description, not the existing code, using this example on fiddle .
7rtdyuoh2#
This should work (untested!):
x
before the ON is an alias which defines how to refer to the results of this sub-query.x.partsID = BOM.partsID
) tells how to glue the two results together,x.supplierName
is used to get the supplierName from the subquery, which we namedx
.NOTE: As was (already noted) in the comments, above is just a simple glue-ing (is that a proper English word?) two queries to one.
Give me some time to get a proper SQL statement... 😉