加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 选择group by子句中的前n行

发布时间:2020-12-12 08:42:48 所属栏目:MsSql教程 来源:网络整理
导读:我有类似于以下的模式: 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_dt
我有类似于以下的模式:
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.

解决方法

交叉应用是你通常这样做 – 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!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读