在内部联接的日期列中获取倒数第二个记录

时间:2018-08-22 03:18:56

标签: sql sql-server

我需要在名为OrderDate的日期列中拉出倒数第二条记录。但是,我只需要带上一个日期(我要在一张包含所有采购订单,日期和成本的表中进行搜索,其中只需要倒数第二个及其成本)。今天(和正在运行)其查询的编写方式为我提供了最新的日期。

select distinct 
    a.PurchaseNum, a.ItemID, a.SupplierNum, a.Location, a.OrderDate, a.Cost
from 
    PurchaseOrder a
inner join 
    (select 
         l.SupplierNum, l.ItemID, l.Location, maxdate = max(l.OrderDate)
     from  
         PurchaseOrder l
     where 
         l.Cost <> 0 
     group by 
         l.SupplierNum, l.itemid, l.Location) l on a.SupplierNum = l.SupplierNumand a.itemid = l.itemid 
                                                and l.Location = a.Location 
                                                and a.OrderDate = l.maxdate

我尝试使用偏移量lag()(但是在联接中曾经有限制,迫使我使用order by并包含dateOrder列,这不是我想要的,因为我们需要只有一个日期)

有点背景:我有一个报告,其中需要显示每个供应商的采购订单的最后成本和倒数第二个成本。带来订单的最后一笔成本很容易,问题是倒数第二笔……这就是我现在遇到的问题。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

如果我对您的理解正确,这是一个使用df1.loc[df1['value'] == 0, 'value'] = [[0, 0, 0]] 返回两个最高的row_number记录的选项:

orderdate

答案 1 :(得分:0)

内部查询按desc排序,外部查询按asc排序。

select distinct top 1 a.*
from PurchaseOrder a
inner join 
(
select Top 2 l.*
 from  PurchaseOrder l
 where 
 l.Cost <> 0 
group by l.SupplierNum, l.itemid, l.Location order by orderdate desc) l
on  a.SupplierNum= l.SupplierNumand a.itemid = l.itemid and l.Location=a.Location and a.OrderDate = l.Orderdate
order by a.orderdate

SELECT TOP 1 * FROM (SELECT * FROM PurchaseOrder a
EXCEPT SELECT TOP (SELECT (COUNT(*)-2) FROM PurchaseOrder a where 
 l.Cost <> 0 
group by l.SupplierNum, l.itemid, l.Location) * FROM PurchaseOrder) A 

SELECT * 
FROM PurchaseOrder a
WHERE OrderDate = ( SELECT MAX(OrderDate) 
               FROM PurchaseOrder
               WHERE Orderdate < ( SELECT MAX(OrderDate) 
                              FROM PurchaseOrder l where 
l.Cost <> 0 
group by l.SupplierNum, l.itemid, l.Location
                            )
             ) ;

SELECT TOP (1) * 
FROM PurchaseOrder
WHERE OrderDate < ( SELECT MAX(OrderDate) 
               FROM PurchaseOrder where ....
             ) 
ORDER BY OrderDate DESC ;