更难以返回MS查询中的最新数据

时间:2014-02-22 18:44:08

标签: sql database duplicate-removal ms-query

我正在转发这个问题。我已经清理了SQL,但仍然有一些重复的结果。我需要找到每个位置的每个itemnum的最新数据。这就是我所拥有的:

SELECT invbalances.itemnum, 
invbalances.curbal, 
inventory.maxlevel, 
inventory.minlevel2, 
inventory.sstock,
inventory.deliverytime, 
invbalances.location, 
inventory.category
FROM MX7PROD.dbo.invbalances invbalances, 
MX7PROD.dbo.inventory inventory
WHERE invbalances.itemnum = inventory.itemnum 
AND invbalances.location = inventory.location 
AND ((inventory.category<>'cstk' 
And inventory.category<>'nore' 
And inventory.category<>'sp') 
AND (invbalances.itemnum Not Like '%n%'))
ORDER BY invbalances.itemnum

1 个答案:

答案 0 :(得分:0)

假设“最新数据”是由每个位置的每个项目的最高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 <> 'nore'
   And inventory.category <> 'sp'
   and invbalances.itemnum not like '%n%'
   and invbalances.curbal =
       (SELECT MAX(x.curbal)
          FROM MX7PROD.dbo.inventory x
         where x.itemnum = invbalances.itemnum
           and x.location = invbalances.location)

请注意,使用括号在where子句中对条件进行分组对结果没有影响,因为您在每一行都使用了AND,因此我将它们取消了。