我在桌子上有各种各样的地段。这些批次通常只出现一次,但可以重复。我希望获得每个产品代码(列)的最新信息,其中最早创建的日期(列)会带回与该批次相关的其他字段(到期日期,仓库等)。
到目前为止,我有以下查询:
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
如何通过选择收到最早日期的地段来删除重复项?
答案 0 :(得分:1)
使用group by
和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;
答案 1 :(得分:0)
仅当没有其他行具有相同的prod_code但更早的日期时,才使用NOT EXISTS
返回行:
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