Oracle - 在应用某些条件之前计算行数

时间:2013-08-28 11:27:20

标签: sql oracle

我想知道在给定查询中没有rownum条件会返回多少行:

SELECT columns
, [number of rows before applying rownum] AS numberofrows
FROM tables
WHERE conditions
AND rownum < 100

是否可以不使用子查询?

3 个答案:

答案 0 :(得分:1)

您可以在嵌套查询中使用COUNT()的分析版本,例如:

SELECT * FROM
(
  SELECT table_name,
    COUNT(*) OVER() AS numberofrows
  FROM all_tables
  WHERE owner = 'SYS'
  ORDER BY table_name
)
WHERE rownum < 10;

无论如何,您需要将其嵌套以在rownum过滤器之前应用order-by以获得一致的结果,否则您将获得一组随机(ish)行。

您还可以使用分析rownum函数替换ROW_NUMBER()

SELECT table_name, cnt FROM
(
  SELECT table_name,
    COUNT(*) OVER () AS numberofrows,
    ROW_NUMBER() OVER (ORDER BY table_name) AS rn
  FROM all_tables
  WHERE owner = 'SYS'
)
WHERE rn < 10;

答案 1 :(得分:0)

您需要运行两个查询。首先找到set的大小,然后找到数据的大小。

select count(*) from tables where conditions;

然后是第二个。

请注意,在您订购套装之前,请将其包装到另一个选择

select * from (select columns from tables where conditions order by columns) rownum < 100

Lecture about limiting resources

答案 2 :(得分:0)

在这种情况下,使用条件聚合:

      select sum(case when conditions then 1 else 0 end) as NumWithConditions,
             count(*) as Total
      from tables;