2009-06-16 73 views
10

选择一个组中的前n行我有类似以下模式:by子句

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

我想查询表,每仪器返回最近的5行。

我可以通过仪器做仪器,具有:

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

我想对所有仪器一次在一个查询做到这一点。这可能吗?我运行SQL Server 2008的

+0

什么版本的SQL Server? – 2009-06-16 21:39:33

+0

SQL Server 2008 - 添加到问题。 – Jon 2009-06-16 21:41:16

回答

12

CROSS APPLY是你平时是怎么做到这一点 - http://msdn.microsoft.com/en-us/library/ms175156.aspx

编辑 - 添加例如,像这样:

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 

通常你会希望通过增加订单在那里。

编辑 - 添加不同的查询,希望可以让你想要你想要的。 编辑 - 在顶部添加缺少“选择”关键字。复制&粘贴错误FTL!

+0

这似乎不适用于我。我认为应用程序在条形表中的每一行上执行时,我得到很多重复的行? – Jon 2009-06-16 22:09:29

7

使用SQL 2008,你可以使用一个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