Question

Id like to return the top three most recent BOOKING_ID, by CREATION_DATE for each active SUPPLIER_ID within a column of bookings.

The active SUPPLIER_ID are gathered with the following query.

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

Is it possible to do this as one query? My current approach is to enter the active SUPPLIER_ID's into a temporary table, and using an outer join to somehow return three records for each supplier.

My expected output is:

SUPPLIER   BOOKING
1          12345
1          54656
1          34546
2          54965
2          05650
2          90565
Was it helpful?

Solution

you could use ranking_functions by partitioning through supplier_id

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 

OTHER TIPS

I think this should do it ??

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

or like other answer by @Vijaykumar Hadalgi using cte and ROW_NUMBER()/RANK() and PARTITION

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top