假设我有一个包含id,color,item的表产品。
select distinct color from product
有没有办法不做一堆工会,从产品表中为每种颜色选择最多2条记录?
我希望能够做一些像
这样的事情select distinct color from product sample 2
答案 0 :(得分:2)
不要使用union
s!只需使用row_number()
:
select p.*
from (select p.*, row_number() over (partition by color order by color) as seqnum
from product p
) p
where seqnum <= 2;
答案 1 :(得分:1)
select id, color, item
from ( select id, color, item,
row_number() over (partition by color order by null) as rn
from product
)
where rn <= 2;