好吧,我在创建查询以从包含以这种方式包含数据的表中检索当前库存时遇到问题: 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最后库存信息。
答案 0 :(得分: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)
答案 1 :(得分: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