使用SQL查询物料最新采购价格的示例

本示例可从SQL Server数据库查得物料在最新采购日期的最小采购价格,即如果同一物料存在多条采购记录,首先取采购日期最大的,如果同一采购日期仍然存在多条记录,取采购价格最低的。(通过调整Order By也可实现其他需求,例如取最早日期或最高采购价格的记录)

--创建临时表,插入测试数据
if Object_id(Tempdb..#temp1) is not null drop table #temp1
create table #temp1(ItemNumber varchar(10),PurchDate date,PurchPrice decimal(10,2))
insert into #temp1(ItemNumber,PurchDate,PurchPrice)
select Item01, 2016-1-8,3.33 union all
select Item01, 2016-5-8,2.22 union all
select Item01, 2016-3-8,1.11 union all
select Item02, 2016-3-9,4.44 union all
select Item02, 2016-5-9,5.55 union all
select Item02, 2016-1-9,6.66 union all
select Item03, 2016-1-7,9.99 union all
select Item03, 2016-3-7,8.88 union all
select Item03, 2016-3-7,7.77
 
--查询所有信息
select * from #temp1 order by ItemNumber asc,PurchDate desc,PurchPrice asc
 
--使用row_number() over partition by 查询物料的最新采购价格,如果同一日期有多个价格取最小值
select *
from (
    select ItemNumber,PurchDate,PurchPrice,
    row_number() over(partition by ItemNumber order by ItemNumber asc,PurchDate desc,PurchPrice asc) row_num
    from #temp1) t1
where t1.row_num=1