SQL Server - 仅选择最新日期

时间:2016-02-16 20:53:28

标签: sql sql-server greatest-n-per-group

RDBMS = Microsoft SQL Server

我在制冷公司工作,我们希望更好地跟踪每个库存地点购买的制冷剂瓶成本。我正在尝试创建一个提取此信息的SQL查询,但我遇到了一些问题。对于每个库存位置,我想显示为该库存位置购买的制冷剂的最后成本。我想查看我们记录该购买特定制冷剂的位置的最新日期。我尝试使用Max函数失败,而Row_Number函数我无法使用。任何帮助将不胜感激。

见下面的代码示例我试图只显示每个库存地点购买的最新日期R-22 30磅水壶。

select 
    lctn_id as Location,
    invntryitm_id as InventoryItemID,
    invntryitm_nme as InventoryItemName,
    prchseordrlst_dte_rqstd as DateRequested,
    prchseordrlst_unt_cst as UnitCost
from 
    invntryitm
join
    prchseordrlst on prchseordrlst.invntryitm_rn = invntryitm.invntryitm_rn
join 
    prchseordr on prchseordr.prchseordr_rn = prchseordrlst.prchseordr_rn
join
    lctn on lctn.lctn_rn = prchseordr.lctn_rn
where   
    invntryitm.invntryitm_nme ='REFRIGERANT R-22 30#'
    and lctn_obslte = 'N'
group by 
    lctn.lctn_id, invntryitm.invntryitm_id, invntryitm.invntryitm_nme, 
    prchseordrlst.prchseordrlst_unt_cst
order by 
    lctn_id

1 个答案:

答案 0 :(得分:2)

我认为分析/窗口功能可以满足您的需求:

with location_data as (
  select 
    lctn_id as Location,
    invntryitm_id as InventoryItemID,
    invntryitm_nme as InventoryItemName,
    prchseordrlst_dte_rqstd as DateRequested,
    prchseordrlst_unt_cst as UnitCost,
    max (prchseordrlst_dte_rqstd) over (partition by lctn_id) as max_date
  from
    invntryitm
    JOIN prchseordrlst on prchseordrlst.invntryitm_rn = invntryitm.invntryitm_rn
    JOIN prchseordr on prchseordr.prchseordr_rn = prchseordrlst.prchseordr_rn
    JOIN lctn on lctn.lctn_rn = prchseordr.lctn_rn
  where
    invntryitm.invntryitm_nme ='REFRIGERANT R-22 30#' and
    lctn_obslte = 'N'
)
select *
from location_data
where max_date = DateRequested
order by Location

请记住,如果有一个平局,两个具有相同日期的location_id记录,那么你将得到它们两个。如果这是一个问题,那么您可能需要row_number()而不是max()

row_number() over (partition by lctn_id order by prchseordrlst_dte_rqstd desc) as rn

然后你会

where rn = 1

获取第一行

我之前没有列出row_number()的原因是max是O(n),如果您的数据有日期和时间,则可能就足够了。< / p>