简体   繁体   English

一对多关系限制为 N 个数

[英]Limit to N number with one-to-many relationship

I'm looking for a way to return 100 unique events which are correlated with several records from another table.我正在寻找一种方法来返回 100 个与另一个表中的多个记录相关的唯一事件。

Normally I would use TOP to return a certain number of records, but I'm dealing with a one-to-many join.通常我会使用 TOP 返回一定数量的记录,但我正在处理一对多连接。

For example, in the included image, I'm looking to return the top three fruits and all of their records as highlighted (or just three fruits in general--not picky on order), but I am not aware of a way to do this in SQL.例如,在包含的图像中,我希望返回前三个水果及其所有突出显示的记录(或者一般只有三个水果——不挑食),但我不知道该怎么做这在 SQL 中。

图片

You could use dense_rank() :你可以使用dense_rank()

select *
from (
    select t.*, dense_rank() over(order by fruit) rn
    from mytable t
) t
where rn <= 3

This gives you all rows for the "first" three fruits, as defined by their alphabetical order.这将为您提供“前”三个水果的所有行,按照它们的字母顺序定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM