我想在表架构上执行SQL查询
Id | BusNo | PartNo |dateAdded
1 | 437 | 2 |2014-02-28
2 | 423 | 3 |2014-03-28
3 | 423 | 3 |2014-04-28
4 | 437 | 2 |2014-03-28
5 | 452 | 1 |2014-03-29
我想在ID
和BusNo
的条件中按日期顺序选择结果PartNo
。结果将是这样的
Id | BusNo | PartNo |dateAdded
3 | 423 | 3 |2014-04-28
4 | 437 | 2 |2014-03-28
5 | 452 | 1 |2014-03-29
我试过
select [Id]
into
from [PartUsed]
where BusNo = @busNo and [PartNo] exists (select ID from @Usertable)
@userTable
是用户定义的表格类型,但它会选择所有行,我希望partNo
按dateAdded
组排序前1位。
答案 0 :(得分:1)
With cte as ( Select id,busno,partno,dateadded,
Row_Number() over( partition by partno order by dateadded desc ) as seqNum
from Partused
)
select id,busno,partno,dateadded
from cte
where seqNum=1
答案 1 :(得分:1)
;with x as (
select *, row_number() over(partition by PartNo order by DateAdded desc) as rn
from PartsUsed
)
select *
from x
where x.BusNo = @busNo
and x.PartNo in (select ID from @Usertable)
and x.rn = 1