开发者

Oracle Bucketing Values

I am trying to write a query to get counts of values in different ranges.

Let us say my table has a column called 'Name' and another column called 'Value' which is numeric.

The 'Value' column can take values from 1 to 1开发者_JAVA百科00.

Currently I am writing a query like

select count(1) from table where value between 1 and 10
union all
select count(1) from table where value between 11 and 80
union all
select count(1) from table where value between 81 and 100.

The query gives me the results but seems to perform veeeeeerrrrry SLOW.

Is there a better way to do this ?

Please remember that I cannot partition the table based on the values in the 'Value' column as I have other columns as well.

Edit

Ok I am going to modify the above query to

select count(distinct names) from table where value between 1 and 10
union all
select count(distinct names) from table where value between 11 and 80
union all
select count(distinct names) from table where value between 81 and 100.


For your first query, assuming you don't care whether you get one row with three columns or three rows with one column, you could do something like

SELECT SUM( CASE WHEN value BETWEEN 1 AND 10
                 THEN 1
                 ELSE 0
             END) num_between_1_and_10,
       SUM( CASE WHEN value BETWEEN 11 AND 80
                 THEN 1
                 ELSE 0
             END) num_between_11_and_80,
       SUM( CASE WHEN value BETWEEN 81 AND 100
                 THEN 1
                 ELSE 0
             END) num_between_81_and_100
  FROM table_name

That will let you scan the table once rather than scanning it three times.

The second query, in general, returns a different result set. You can match your second query with a different query

SELECT COUNT( DISTINCT( CASE WHEN value BETWEEN 1 AND 10
                             THEN name
                             ELSE null
                         END) ) num_distinct_between_1_and_10,
       COUNT( DISTINCT( CASE WHEN value BETWEEN 11 AND 80
                             THEN name
                             ELSE null
                         END) ) num_distinct_between_11_and_80,
       COUNT( DISTINCT( CASE WHEN value BETWEEN 81 AND 100
                             THEN name
                             ELSE null
                         END) ) num_distinct_between_81_and_100
  FROM table_name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜