我对 SQL 比较陌生——上周才开始使用它。我在通过基于连接的索引将 2 个表连接在一起时遇到了一些问题(我可以这样做,但它会显示几个日期)然后按最大日期过滤它
请参阅下面的第一个版本,该版本显示了连接在一起的表格。我需要加入两个表。INVENTORY_TRANSACTION_HIST2(作业)inventory_transaction_hist(与项目细节相关的更多细节)
这些表之间没有关联,因此我不得不从几个字段中构建连接的表:
part_no||lot_batch_no||serial_no||location_no
用于两个表之间的关联。
order_no||release_no||sequence_no||line_item_no
仅与第二个表相关并创建过滤日期所需的索引
select
to_char(job.dated,'dd/mm/yyyy hh:mm:ss') date_issued,
job.userid,
job.part_no,
job.quantity,
job.lot_batch_no,
job.serial_no,
job.cost,
job.quantity* job.cost total_cost,
job.source note,
hist.dated,
hist.order_no,
hist.release_no,
hist.sequence_no,
hist.line_item_no
from
inventory_transaction_job job
left join inventory_transaction_hist hist
on job.part_no||job.lot_batch_no||job.serial_no||job.location_no = hist.part_no||hist.lot_batch_no||hist.serial_no||hist.location_no
where (job.source like UPPER('%'||'&Job_No'||'%') or job.source like LOWER('%'||'&Job_No'||'%'))
and hist.transaction LIKE '%INM-IN%'
and hist.direction LIKE '+'
order by job.part_no
我需要按历史上最近的日期进一步划分。表(因为某些批次/序列号仅显示为“*”,因此可以针对每个显示多个订单号 - 我只想显示这些订单的最新订单)
我已经尝试了以下和其他一些变化,但我似乎无法让它工作。
select
to_char(job.dated,'dd/mm/yyyy hh:mm:ss') date_issued,
job.userid user_id,
job.part_no,
job.quantity,
job.lot_batch_no,
job.serial_no,
job.cost,
job.quantity* job.cost total_cost,
job.source note,
hist.dated,
hist.order_no,
hist.release_no,
hist.sequence_no,
hist.line_item_no
from
inventory_transaction_job job
left join inventory_transaction_hist hist
on job.part_no||job.lot_batch_no||job.serial_no||job.location_no = hist.part_no||hist.lot_batch_no||hist.serial_no||hist.location_no
where (job.source like UPPER('%'||'&Job_No'||'%') or job.source like LOWER('%'||'&Job_No'||'%'))
and hist.transaction LIKE '%INM-IN%'
and hist.direction LIKE '+'
and job.order_no||job.sequence_no||job.line_item_no IN
(SELECT
hist2.order_no||hist2.sequence_no||hist2.line_item_no
FROM inventory_transaction_hist hist2
WHERE job.part_no||job.lot_batch_no||job.serial_no||job.location_no LIKE hist2.part_no||hist2.lot_batch_no||hist2.serial_no||hist2.location_no
ORDER BY hist2.Dated DESC LIMIT 1)
任何帮助将不胜感激。