Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle aggregate function to return a random value for a group?

The standard SQL aggregate function max() will return the highest value in a group; min() will return the lowest.

Is there an aggregate function in Oracle to return a random value from a group? Or some technique to achieve this?

E.g., given the table foo:

group_id value
1        1
1        5
1        9
2        2
2        4
2        8

The SQL query

select group_id, max(value), min(value), some_aggregate_random_func(value)
from foo
group by group_id;

might produce:

group_id  max(value), min(value), some_aggregate_random_func(value)
1        9            1           1
2        8            2           4

with, obviously, the last column being any random value in that group.

like image 736
tpdi Avatar asked Jun 18 '10 01:06

tpdi


1 Answers

You can try something like the following

select deptno,max(sal),min(sal),max(rand_sal) 
from(
select deptno,sal,first_value(sal) 
     over(partition by deptno order by dbms_random.value) rand_sal
from emp)
group by deptno
/

The idea is to sort the values within group in random order and pick the first.I can think of other ways but none so efficient.

like image 87
josephj1989 Avatar answered Oct 25 '22 13:10

josephj1989