查询始终返回固定数量的行

时间:2018-04-26 08:32:42

标签: sql oracle

我可以编写一个查询,以产品类别为基础返回前5个产品的销售数字。但是,如果我们说产品类别只有2个产品,那么只返回2行。

是否可以插入虚拟行,以便每个产品类别始终返回5行。虚拟行只需要具有正确的产品类别和剩余列的空值。

1 个答案:

答案 0 :(得分:0)

使用UNION ALL添加额外的行,然后过滤以仅保留5

SELECT *
FROM   (
  SELECT col1, col2
  FROM   your_table
  WHERE  ROWNUM <= 5
UNION ALL
  SELECT NULL, NULL FROM DUAL CONNECT BY LEVEL <= 5
-- ORDER BY col1 NULLS LAST, col2 NULLS LAST -- If necessary
)
WHERE  ROWNUM <= 5

或者如果你是为多个群体做这件事:

WITH categories ( category, col1, rn ) AS (
  SELECT category,
         col1,
         ROW_NUMBER() OVER ( PARTITION BY category ORDER BY col1 )
  FROM   products
)
SELECT category,
       col1
FROM   (
  SELECT category,
         col1,
         ROW_NUMBER() OVER ( PARTITION BY category ORDER BY rn ) AS rn
  FROM   (
    SELECT category,
           col1,
           rn
    FROM   categories
    WHERE  rn <= 5
  )
  UNION ALL
  (
     SELECT category,
            NULL,
            5 + LEVEL
     FROM   categories
     WHERE  rn = 1
     CONNECT BY LEVEL <= 5
  )
)
WHERE  rn <= 5;