我有一张订购的物品表。 表字段:PONumber,OrderDate,itemNumber,Description,Cost
由于我可以在不同日期多次订购商品,因此我想返回最近的日期,但仍然包含所有字段。
表格
PONumber OrderDate itemNumber Description Cost
123 01/01/2016 A235 Bolt 1.13
142 02/22/2016 A235 Blot 2.10
166 03/01/2016 A444 Screw 1.22
411
返回
PONumber OrderDate itemNumber Description Cost
142 02/22/2016 A235 Blot 2.10
166 03/01/2016 A444 Screw 1.22
我尝试了一个完整的查询,但是我必须删除“费用”字段,否则它会显示所有记录,我需要显示费用。
SELECT PONumber, Max(OrderDate), itemNumber, Description, Cost
FROM tblItemsOrdered
GROUP BY PONumber, OrderDate, itemNumber, Description, Cost;
答案 0 :(得分:2)
查找子查询中每个项目的最新订单日期,并将其与原始表格连接,如下所示:
header {
padding-top: 1px;
}
请注意,如果所有这些行都有最新的orderDate,这将为同一itemNumber返回多行。
select t1.*
from tblItemsOrdered t1
inner join (
SELECT itemNumber, Max(OrderDate) as Max_OrderDate
FROM tblItemsOrdered
GROUP BY itemNumber
) t2 on t1.itemNumber = t2.itemNumber
and t1.OrderDate = t2.Max_OrderDate;
或者如果PONumber是唯一的:
select t1.*
from tblItemsOrdered t1
inner join (
select t1.itemNumber, t1.OrderDate, max(t1.PONumber) as max_PONumber
from tblItemsOrdered t1
inner join (
SELECT itemNumber, Max(OrderDate) as Max_OrderDate
FROM tblItemsOrdered
GROUP BY itemNumber
) t2 on t1.itemNumber = t2.itemNumber
and t1.OrderDate = t2.Max_OrderDate
group by t1.itemNumber, t1.OrderDate
) t2 on t1.itemNumber = t2.itemNumber
and t1.PONumber = t2.max_PONumber
and t1.OrderDate = t2.OrderDate;
答案 1 :(得分:1)
这不是group by
。您想要所有列,请考虑where
进行过滤:
select o.*
from tblItemsOrdered as o
where o.OrderDate = (select max(o2.OrderDate)
from tblItemsOrdered as o2
where o2.itemNumber = o.itemNumber
);
注意:如果该项目在最近的日期被多次订购,那么这将返回所有行。