简体   繁体   中英

Select query on temp table without using cursor SQL

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 .

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
    ;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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM