0

好吧,我在创建查询以从包含以下数据的表中检索当前库存时遇到问题:ID、仓库、日期、库存

我想得到的是最新的股票变化日期的当前股票信息。

例如:

1, A, 2013-01-01, 1  
1, A, 2013-01-02, 2  
1, A, 2013-01-03, 4  
1, A, 2013-01-05, 1  
1, B, 2013-01-01, 1  
1, B, 2013-01-02, 2  
1, B, 2013-01-03, 4  
2, B, 2013-01-01, 1  
2, B, 2013-01-02, 2  
2, B, 2013-01-03, 4  

结果我想:

1, A, 2013-01-05, 1  
1, B, 2013-01-03, 4  
2, B, 2013-01-03, 4  

对于每个 ID,每个仓库的最后库存信息。

4

2 回答 2

1

如果您拥有或将获得其他列,此版本仍然有效,而无需添加带有 TOP、排序等的新行 :)

select *
from TableName t1
where t1.Date = 
      (select max(t2.Date) 
         from TableName t2
        where t2.Id = t1.id and t2.Warehouse = t1.WareHouse)
于 2013-11-13T13:42:45.720 回答
0
SELECT t1.ID, t1.Warehouse, t1.Date, Stock
FROM TestTable t1
JOIN
(
    SELECT ID, Warehouse, MAX(Date) [Date]
    FROM TestTable
    GROUP BY ID, Warehouse
) t2 ON t1.ID = t2.ID
    AND t1.Warehouse = t2.Warehouse
    AND t1.Date = t2.Date
ORDER BY ID, Warehouse
于 2013-11-13T13:48:35.800 回答