【发布时间】:2014-04-17 21:37:44
【问题描述】:
我一直在尝试编写一个查询,通过发布日期并忽略其余行来仅选择表中每个“Item No_”中最新的。我一直收到各种错误。最后一个令人烦恼,因为此时我看不到错误。这是查询的sn-p:
SELECT ri.*
FROM [Rigid Industries$Item Ledger Entry] ri
INNER JOIN
(SELECT DISTINCT [Item No_], MAX([Posting Date]) AS maxDate
FROM [Rigid Industries$Item Ledger Entry]
WHERE maxDate <= CONVERT(datetime, '2014-01-17 02:33:16.939')
GROUP BY maxDate, [Item No_]]
) itDat
ON ri.[Item No_] = itDat.[Item No_]
WHERE ri.[Quantity] > 0
ORDER BY ri.[Location Code] DESC, ri.[Item No_] ASC, ri.[Posting Date] DESC;
在 Peter G 和 rs 的帮助下,我找到了解决方案。
SELECT E.*
FROM [Rigid Industries\$Item Ledger Entry] E
WHERE [Posting Date] =
(SELECT MAX(x.[Posting Date])
FROM [Rigid Industries\$Item Ledger Entry] x
WHERE x.[Item No_] = E.[Item No_]
AND x.[Posting Date] <= CONVERT(datetime, '$dateYo')
) AND
[Entry No_] =
(SELECT MAX(y.[Entry No_])
FROM [Rigid Industries\$Item Ledger Entry] y
WHERE y.[Item No_] = E.[Item No_]
)
AND E.[Quantity] > 0
ORDER BY E.[Location Code] DESC, E.[Item No_] ASC, E.[Posting Date] DESC;
【问题讨论】:
-
SELECT E.* FROM [Rigid Industries\$Item Ledger Entry] E WHERE [Posting Date] = (SELECT MAX(x.[Posting Date]) FROM [Rigid Industries\$Item Ledger Entry] x WHERE x.[Item No_] = E.[Item No_] AND x.[Posting Date] 0 ORDER BY E.[Location Code] DESC, E.[Item No_ ] ASC, E.[发布日期] DESC;