假设我有一对多关系,并希望在某些JOIN_ID上连接两个表,但是对于每个不同的JOIN_ID,我想将结果中的行数限制为n。我该怎么做?
* Oracle SQL
答案 0 :(得分:1)
我会这样做:
select t1.*, t2.*
from t1 join
(select t2.*,
row_number() over (partition by joinkey order by ??) as seqnum
from t2
) t2
on t1.joinkey = t2.joinkey and seqnum <= 6;
??
用于指定定义要键入的行的顺序。例如,order by id desc
会保留具有最高ID的行。
答案 1 :(得分:0)
如果您的RDBMS支持row_number()
,那么您可以执行以下操作:
select *
from (
select
t1.*
, t2.*
, row_number() over (partition by t1.join_id order by t2.id) as rn
from t1
inner join t2
on t1.join_id = t2.join_id
) as s
where rn < 6