限制SQL结果

时间:2018-06-27 16:29:51

标签: sql oracle

我有一个查询,试图从表中获取结果:

SELECT P.P_CODE, P.P_JEWELRYTYPE,P.p_catalog, P_AVAILABLE, P_RESERVED , p.p_catalog
FROM products P 
WHERE 
P.p_catalog IN (8796093383256,8796093252184,8796093317720,8796093121112,8796093186648);

我想要一个查询,其中可以将每种目录类型的结果数限制为500。我应该如何修改查询以实现此目的?

2 个答案:

答案 0 :(得分:0)

使用row_number()

select p.*
from (select p.*, row_number() over (partition by catalog order by null) as seqnum
      from products p
     ) p
where p.seqnum <= 500;

您可以将where过滤放入内部或外部查询中。

答案 1 :(得分:0)

分析功能row_number()将起作用,它将为每个p_catalog分配行号,以便您可以在外部查询的WHERE子句中根据该条件进行过滤:

SELECT *
FROM (
  SELECT 
    p.P_CODE, p.P_JEWELRYTYPE, p.p_catalog, p.P_AVAILABLE, p.P_RESERVED, p.p_catalog,
    row_number() over (partition by p.p_catalog) as rn
  FROM products p
  WHERE p.p_catalog IN (8796093383256,8796093252184,8796093317720,8796093121112,8796093186648)
) p
WHERE rn <= 500;