views:

92

answers:

1

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.

+5  A: 

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.

josephj1989
Wow, I'd have thought "order by dbms_random.value" would be interpreted as a column number. But testing shows this works. Thanks.
tpdi