SQL - 从查询中删除重复项

时间:2016-06-07 07:07:20

标签: sql

我正在尝试创建一个不会返回具有相同No_的行的SQL查询。 如何删除No_列中的重复项?我想只保留基于上一个发布日期列的数据。

select  Item.No_, Entry.[Posting Date], Entry.[Remaining Quantity], MinMax.Maximum
FROM Item
join Entry
on Item.No_ = Entry.[Item No_]
join MinMax
 on Item.No_ = MinMax.Item No_
order by  Entry.[Remaining Quantity] desc

输出:

enter image description here

但我希望输出是上次发布日期:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用包含每No_的最新日期的派生表:

select  Item.No_, 
        Entry.[Posting Date], Entry.[Remaining Quantity], 
        MinMax.Maximum
FROM Item
join (
   select max([Posting Date]) as max_Date, [Item No_]
   from Entry
   group by [Item No_]
) as e on e.[Item No_] = Item.No_
join Entry on Item.No_ = Entry.[Item No_] and e.max_Date = Entry.[Posting Date]
join MinMax on Item.No_ = MinMax.Item No_
order by  Entry.[Remaining Quantity] desc

加入此衍生表会过滤掉与每[Posting Date]最新No_的记录无关的记录。