SQL根据不同表中的最大日期选择

时间:2012-10-24 16:52:33

标签: sql

我正在尝试编写一个从各种表中提取订单信息的查询。我已经达到了目标日期值的路障。

似乎每次更改目标日期时,都会在该表中添加新行。我想要的是只能选择最新的目标日期。我该怎么办?

 select Distinct
 OR01001 AS OrderNumber,
 OR01002 AS OrderType,
 OR01003 AS CustomerCode,
 OR01015 AS OrderDate,
 OR01017 AS CustomerREP,
 OR01018 AS ContactPerson,
 OR01019 AS SalesmanNumber,
 OR03011 - OR03012 AS OpenQuantity,
 SC03003 AS StockBalance,
 OR01050 AS WarehouseNumber,
 OR01072 AS CustomerPO,
 OR03005 AS ItemCode,
 OR03002 AS LineNumber,
 OR500100.OR50004 As TargetDate
 from OR010100
 INNER Join OR030100 ON OR030100.OR03001 = OR010100.OR01001
 INNER Join SL010100 ON SL010100.SL01001 = OR010100.OR01003
 INNER Join SC030100 ON SC030100.SC03001 = OR030100.OR03005 
 Inner JOIN OR500100 ON OR500100.OR50001 = OR010100.OR01001 
 where OR010100.OR01002 <> 0 AND OR010100.OR01002 <> 6 AND OR01017 = 'SLOTT' 
 Order by OR01017 ASC;

2 个答案:

答案 0 :(得分:1)

如果我正确理解你的列,这是一种方式:

SELECT ...,
    OR500100A.OR50004 AS TargetDate
FROM ...
INNER JOIN OR500100 AS OR500100A ON OR500100A.OR50001 = OR010100.OR01001 
    AND NOT EXISTS(SELECT 1 FROM OR500100 AS OR500100B 
                   WHERE OR500100B.OR5001 = OR010100.OR01001 
                   AND OR500100B.OR50004 > OR500100A.OR50004)
...

这样,您就可以确保只有OR500100的{​​{1}}行获得给定OR50004 OR5001的最新值。

答案 1 :(得分:1)

据我所知,

SELECT
...
MAX(OR500100.OR50004) As TargetDate
FROM...
WHERE...
GROUP BY --everything but OR500100.OR50004
ORDER BY...

应该做的伎俩

编辑:ty Ic。