我的表(名为Inventory)如下:
InventoryType,LocationID,InventoryLevel,SafetyStock,MaxLevel,ModifiedAt
Erasors,1,14,3,15,11-2014
Erasors,2,4,10,50,10-2014
Erasors,2,5,10,50,11-2014
铅笔,1,10,5,45,11-2014
铅笔,2,23,15,50,11-2014
笔,1,9,10,50,11-2014
笔,2,55,10,50,12-2014
有三个主键:InventoryType,LocationID和ModifiedAt。
给定指定的LocationID,我希望查询为每个不同的InventoryType返回all,其中返回的每个元组的日期是具有指定LocationID的给定库存类型的记录中的最新ModifiedAt日期。例如,LocationID = 2将返回:
InventoryType,LocationID,InventoryLevel,SafetyStock,MaxLevel,ModifiedAt
Erasors,2,5,10,50,11-2014
铅笔,2,23,15,50,11-2014
笔,2,55,10,50,12-2014
到目前为止,我的尝试如下:
SELECT InventoryType, LocationID, InventoryLevel,
SafetyStock, MaxLevel, ModifiedAt
FROM Inventory
WHERE LocationID = 2 AND ModifiedAt IN
(SELECT TOP 1 ModifiedAt
FROM Inventory
WHERE LocationID = 2
ORDER BY ModifiedAt DESC);
我的查询返回:
InventoryType,LocationID,InventoryLevel,SafetyStock,MaxLevel,ModifiedAt
Pens,2,55,10,50,12-2014
任何帮助都将不胜感激。
答案 0 :(得分:1)
您需要一个相关的子查询。试试这个:
SELECT InventoryType, LocationID, InventoryLevel, SafetyStock, MaxLevel, ModifiedAt
FROM Inventory as i
WHERE LocationID = 2 AND
ModifiedAt IN (SELECT TOP 1 i2.ModifiedAt
FROM Inventory as i2
WHERE i2.LocationID = 2 AND i2.InventoryType = i.InventoryType
ORDER BY i2.ModifiedAt DESC
);
答案 1 :(得分:0)
使用SELECT DISTINCT
选择不同的InventoryType
。
SELECT DISTINCT InventoryType, LocationID,
InventoryLevel, SafetyStock, MaxLevel, ModifiedAt
FROM Inventory
WHERE LocationID = 2
AND ModifiedAt IN
(SELECT TOP 1 ModifiedAt FROM Inventory WHERE LocationID = 2 ORDER BY ModifiedAt DESC)