SQL Server 2008 - 为每个供应商选择最后3个预订ID

时间:2013-12-27 10:08:31

标签: sql sql-server rank

我想在预订列中为每个有效BOOKING_IDCREATION_DATE返回前三个SUPPLIER_ID

使用以下查询收集活动SUPPLIER_ID

select SUPPLIER_ID 
into #active 
from BookingTable 
where BOOKING_ID in (select BOOKING_ID 
                     from BookingTable 
                     where CREATION_DATE > getdate() - 90) 
group by SUPPLIER_ID

是否可以将此作为一个查询执行?我当前的方法是将活动SUPPLIER_ID输入临时表,并使用外连接以某种方式为每个供应商返回三条记录。

我的预期输出是:

SUPPLIER   BOOKING
1          12345
1          54656
1          34546
2          54965
2          05650
2          90565

2 个答案:

答案 0 :(得分:2)

您可以通过supplier_id

进行分区来使用ranking_functions
WITH cte 
     AS (SELECT *, 
                Row_number() 
                  OVER( 
                    partition BY supplier 
                    ORDER BY creation_date DESC) AS rn 
         FROM   table) 
SELECT * 
FROM   cte 
WHERE  rn <= 3 

答案 1 :(得分:0)

我认为应该这样做?

select top 3 from table order by CREATION_DATE desc group by SUPPLIER_ID

或者像@Vijaykumar Hadalgi使用cte和ROW_NUMBER()/ RANK()和PARTITION

一样的其他答案