0

这是我的代码!我想在我的报告中提供零件 ID 和采购订单 ID,它会带来所有相关信息以及这些规范。重要的是,如果我们有相同的采购订单 ID 和零件 ID,我们需要代码来返回具有最高交易 ID 的结果。以下代码没有提供我所期望的。请你帮助我好吗?

SELECT MAX(INVENTORY_TRANS.TRANSACTION_ID), INVENTORY_TRANS.PART_ID
, INVENTORY_TRANS.PURC_ORDER_ID, TRACE_INV_TRANS.QTY, TRACE_INV_TRANS.CREATE_DATE, TRACE_INV_TRANS.TRACE_ID
FROM INVENTORY_TRANS    
JOIN TRACE_INV_TRANS ON INVENTORY_TRANS.TRANSACTION_ID = TRACE_INV_TRANS.TRANSACTION_ID    
WHERE INVENTORY_TRANS.PART_ID = @PartID 
    AND INVENTORY_TRANS.PURC_ORDER_ID = @PurchaseOrderID    
GROUP BY TRACE_INV_TRANS.QTY, TRACE_INV_TRANS.CREATE_DATE, TRACE_INV_TRANS.TRACE_ID, INVENTORY_TRANS.PART_ID
, INVENTORY_TRANS.PURC_ORDER_ID

trace_inventory_trans 表的示例是:

part_id   trace_id    transaction id     qty       create_date     
x           1             10
x           2             11
x           3             12

inventory_trans 表的样本是:

transaction_id     part_id     purc_order_id
11                 x            p20
12                 x            p20

我想获得最大交易的结果,即交易 12,但它显示了交易 11

4

1 回答 1

0

我会使用子查询来查找MAX值,然后将该结果连接到另一个表。

ORDER BY+TOP (1)返回的MAXtransaction_id

SELECT 
   inv.transaction_id
  ,inv.part_id
  ,inv.purc_order_id
  ,tr.qty
  ,tr.create_date
  ,tr.trace_id
FROM 
  (
    SELECT TOP (1)
      transaction_id,
      part_id,
      purc_order_id
    FROM 
      INVENTORY_TRANS
    WHERE 
      part_id = @PartID
      AND 
      purc_order_id = @PurchaseOrderID
    ORDER BY 
      transaction_id DESC
  ) AS inv
JOIN 
  TRACE_INV_TRANS AS tr
    ON inv.transaction_id = tr.transaction_id;

结果:

+----------------+---------+---------------+------+-------------+----------+
| transaction_id | part_id | purc_order_id | qty  | create_date | trace_id |
+----------------+---------+---------------+------+-------------+----------+
|             12 | x       | p20           | NULL | NULL        |        3 |
+----------------+---------+---------------+------+-------------+----------+

Rextester 演示

于 2020-04-21T19:53:31.860 回答