选择 group by 子句中的前 n 行

编程入门 行业动态 更新时间:2024-10-26 12:30:59
本文介绍了选择 group by 子句中的前 n 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的架构类似于以下内容:

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 )

我想查询表格,并返回每个工具最近的 5 行.

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

我想在一个查询中一次为所有仪器执行此操作.这可能吗?我正在运行 SQL Server 2008.

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 是您通常执行此操作的方式 - msdn.microsoft/en-us/library/ms175156.aspx

CROSS APPLY is how you usually do this - msdn.microsoft/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.

编辑 - 为查询添加了不同的内容,希望能满足您的需求.编辑 - 在顶部添加了缺少的选择"关键字.复制&粘贴错误 FTL!

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

更多推荐

选择 group by 子句中的前 n 行

本文发布于:2023-10-14 22:45:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:句中   group

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!