Question

I want perform SQL query on table schema

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

I would like to select results top ID order by date with where condition on BusNo and PartNo.Result would be like this

Id | BusNo | PartNo |dateAdded
3  | 423   | 3      |2014-04-28
4  | 437   | 2      |2014-03-28
5  | 452   | 1      |2014-03-29

I tried

select [Id] 
into  
from [PartUsed] 
where BusNo = @busNo and [PartNo] exists (select ID from @Usertable) 

@userTable is user defined table type, but it will select all rows and I want top 1 in partNo group order by dateAdded.

Was it helpful?

Solution

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

OTHER TIPS

    ;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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top