简体   繁体   中英

SQL Query to return the instance of a column value but return additional fields

I have various lots in a table. These lots usually occur once but could be duplicated. I want to get every lot for a certain product code (column) with the earliest created date (column) bringing back additional fields associated to that lot (expiry date, warehouse etc.).

So far I have the following query:

SELECT DISTINCT lot_number, prod_code, date_received, expiry_date, quantity 
FROM scheme.stquem  
WHERE prod_code = '001'  
AND lot_number != ''     //removes blanks   
ORDER BY lot_number

How could you remove the duplicates by choosing the lot with the earliest date received?

Use group by and join :

SELECT s.lot_number, s.prod_code, s.date_received, s.expiry_date, s.quantity 
FROM scheme.stquem s JOIN
     (SELECT lot_number, min(date_received) as mindr
      FROM scheme.stquem
      WHERE prod_code = '001' AND lot_number <> ''     //removes blanks   
      GROUP BY lot_number
     ) sl
     ON sl.lot_number = s.lot_number and sl.mindr = s.date_received 
WHERE prod_code = '001'
ORDER BY s.lot_number;

Use NOT EXISTS to return a row only if there are no other row with same prod_code but earlier date:

SELECT lot_number, prod_code, date_received, expiry_date, quantity 
FROM scheme.stquem st1
WHERE prod_code = '001'  
AND lot_number != ''     //removes blanks   
AND NOT EXISTS (select 1 from scheme.stquem st2
                where st1.prod_code = st2.prod_code
                  and st2.date_received < st1.date_received)
ORDER BY lot_number

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