简体   繁体   中英

Selecting the top n rows within a group by clause

I have schema similar to the following:

create table bar
(
    instrument varchar(255) not null,
    bar_dttm datetime not null,
    bar_open int not null,
    bar_close int not null
)

I would like to query the table, and return the most recent 5 rows per instrument.

I can do it instrument by instrument, with:

select top 5 instrument, bar_dttm, bar_open, bar_close
from bar
where instrument = 'XXX'
order by bar_dttm desc

I'd like to do this for all instruments at once in one query. Is this possible? I am running SQL Server 2008.

CROSS APPLY is how you usually do this - http://msdn.microsoft.com/en-us/library/ms175156.aspx

EDIT - add example, something like this:

select
    bar1.instrument
    ,bar2.*
from (
    select distinct instrument from bar) as bar1
cross apply (
    select top 5
        bar2.instrument
        ,bar2.bar_dttm
        ,bar2.bar_open
        ,bar2.bar_close 
    from bar as bar2 where bar2.instrument = bar1.instrument) as bar2

Typically you would want to add an order by in there.

Edit - added distinct to the query, hopefully that gives you want you want. Edit - added missing 'select' keyword at top. copy & paste bug FTL!

using SQL 2008, you could use a partitioned row number clause with a CTE...

with MyCte AS (SELECT      instrument, 
                           bar_dttm, 
                           bar_open, 
                           bar_close,
                           PartitionedRowNum = ROW_NUMBER() OVER (PARTITION BY instrument ORDER BY bar_dttm DESC)
               from        bar)
select  *
from    MyCte
where   PartitionedRowNum <= 5

Row_Number can also be used - http://msdn.microsoft.com/en-us/library/ms186734.aspx

WITH foo as (
Select
 *
 ,ROW_NUMBER() OVER(PARTITION BY instrument ORDER BY bar_dttm desc) as rank
from
 bar
)

select 
 *
from
 foo
where
 rank <= 5

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