Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Statistical Mode calc in SQL

Status
Not open for further replies.

DianeJ

Programmer
Sep 22, 2000
15
0
0
CA
I'm looking for the best way to implement the statistical mode calculation in SQL.

Mode is value in a list that occurs the most often. For example I have a table (Temp) that has a column (TempCol) with the following rows:
a
b
a
c
a
a

The mode of these rows would be 'a'.

This is the code that I have so far, is it the best?

select distinct_values.tempcol
from (select tempcol, count(tempcol) occurence
from temp
group by tempcol) distinct_values
where distinct_values.occurence =
(select max(distinct_values.occurence)
from (select tempcol, count(tempcol) occurence
from temp
group by tempcol) distinct_values)


Thanks
Diane
 
You could use a rank function:

select * from
(select tempno, count(tempno),
rank() over (order by count(tempno) desc) as occur_rank
from temp
group by tempno)
where occur_rank < 2
 
SELECT TempCol FROM
(SELECT TempCol, rownum rn FROM
(select count(*) cnt, TempCol
from Temp
group by TempCol)
Order by cnt desc)
WHERE rn = 1

Will also work, If you are not familiar with Analytical functions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top