简体   繁体   中英

SQL - Return a value if all rows that have the same “order number” in one column have the same “slot” in another

I have a table oeordhdr_sql that holds all information for an order using Ord_No as a unique ID. In another table wsPKG I have information stored per pallet. A pallet can be associated to be shipped out on a specific order in which case it gets a value in Org_Ord_No to associate it to the order in oeordhdr_sql . I have an INNER JOIN with an ltrim on both to match the pallet to the order. Since there can be multiple pallets associated to one order we move each pallet to a Bin ( Bin_No ) called TRK to show that it has been shipped.

So far I have this code

SELECT oeordhdr_sql.ord_no, wsPKG.Bin_no
FROM wsPKG
INNER JOIN oeordhdr_sql ON LTRIM(wsPKG.Org_Ord_no) = LTRIM(oeordhdr_sql.ord_no) 
WHERE wsPKG.Bin_no = 'TRK'

Which returns multiple lines for the same order.

   23708    TRK     
   23769    TRK     
   23769    TRK      
   23769    TRK     
   23769    TRK     
   23708    TRK     
   23708    TRK     

I would like to be able to return a value for my shipping manager to show when all pallets associated to a specific order are located in TRK. That value could be Shipped. Eventually I would also have a status of Loading for if some are in TRK but not all.

I think you want a GROUP BY and HAVING :

SELECT oh.ord_no
FROM wsPKG p INNER JOIN
     oeordhdr_sql oh
     ON ltrim(p.Org_Ord_no) = ltrim(oh.ord_no) 
GROUP BY oh.ord_no
HAVING MIN(p.Bin_no) = 'TRK' AND MIN(p.Bin_no) = MAX(p.Bin_no)

This returns all the oh.ord_no s where all bin numbers are 'TRK' (it ignores NULL s, so if the data has NULL s you might want to specify what to do with those bin numbers.

Note: The JOIN condition is suspicious. There should be no reason to use TRIM() on JOIN keys between related tables. If the keys are numbers, this is meaningless. If the keys are strings, they should be stored without leading or trailing spaces.

Try the following:

Select DISTINCT OS.ord_no, WP.Bin_no
FROM wsPKG WP
LEFT JOIN oeordhdr_sql OS on ltrim(WP.Org_Ord_no)=ltrim(OS.ord_no) AND WP.Bin_no='TRK'

HTH

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM