仅返回包含多个链接表的数据库查询中的最新条目

时间:2014-02-22 16:51:10

标签: sql database ms-query

我认真对待这个...... 我有一个MS查询与3个链接表返回多个结果。我需要将它们限制为最近的条目,因为数据太大而无法导入到Excel中。这是当前正在使用的SQL的副本。我需要根据字段inventory.lastissuedate

消除除最新条目以外的所有条目
SELECT invbalances.itemnum
     , invbalances.curbal
     , inventory.maxlevel
     , a_inventory52.minlevel
     , inventory.sstock
     , inventory.deliverytime
     , inventory.category
     , inventory.lastissuedate
FROM MX7PROD.dbo.a_inventory52 a_inventory52
    , MX7PROD.dbo.invbalances invbalances, MX7PROD.dbo.inventory inventory
WHERE invbalances.itemnum = inventory.itemnum 
AND a_inventory52.itemnum = invbalances.itemnum 
AND ((inventory.category<>'cstk' 
And inventory.category<>'ns' 
And inventory.category<>'nore' 
And inventory.category<>'sp'))

2 个答案:

答案 0 :(得分:0)

尝试在最后添加:

AND inventory.lastissuedate = 
(SELECT MAX(lastissuedate) FROM MX7PROD.dbo.inventory)

答案 1 :(得分:0)

编辑使用表invbalances.location作为位置字段。

这会将您的数据限制为curbal是指定项目和位置的最后一个curbal的行。

SELECT invbalances.itemnum,
       invbalances.curbal,
       inventory.maxlevel,
       a_inventory52.minlevel,
       inventory.sstock,
       inventory.deliverytime,
       inventory.category,
       inventory.lastissuedate
  FROM MX7PROD.dbo.a_inventory52 a_inventory52,
       MX7PROD.dbo.invbalances   invbalances,
       MX7PROD.dbo.inventory     inventory
 WHERE invbalances.itemnum = inventory.itemnum
   AND a_inventory52.itemnum = invbalances.itemnum
   AND inventory.category <> 'cstk'
   And inventory.category <> 'ns'
   And inventory.category <> 'nore'
   And inventory.category <> 'sp'
   and invbalances.curbal =
       (SELECT MAX(x.curbal)
          FROM MX7PROD.dbo.inventory x
         where x.itemnum = invbalances.itemnum
           and x.location = invbalances.location)