簡體   English   中英

在臨時表上選擇查詢而不使用游標SQL

[英]Select query on temp table without using cursor SQL

我想在表模式上執行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按日期排序,其中BusNoPartNo上的條件BusNo將是這樣的

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組中排名前1,按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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM