Mean is the same as average. Median has been beaten to death. Let's write a query to calculate Mode.
Mode is essentially the value the occurs most often. For this teaser, let's write a query that calculates the Mode of a sample. For example, from the following set of values [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17], 6 occurs most often, and is therefore the mode of this sample. If the mode is not unique, then we should return NULL. For example, in this set [1, 1, 2, 4, 4] 1 and 4 both occur most often, so the mode (returned from our query) should be NULL.
The challenge is to write a query that calculates the Mode for each id. The output of this query should be...
[tt][blue]
Id Mode
----- ------
1 6
2 NULL
[/blue][/tt]
-George
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
Mode is essentially the value the occurs most often. For this teaser, let's write a query that calculates the Mode of a sample. For example, from the following set of values [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17], 6 occurs most often, and is therefore the mode of this sample. If the mode is not unique, then we should return NULL. For example, in this set [1, 1, 2, 4, 4] 1 and 4 both occur most often, so the mode (returned from our query) should be NULL.
Code:
Declare @Temp Table(Id Int, Value Int)
Insert Into @Temp Values(1,1)
Insert Into @Temp Values(1,3)
Insert Into @Temp Values(1,6)
Insert Into @Temp Values(1,6)
Insert Into @Temp Values(1,6)
Insert Into @Temp Values(1,6)
Insert Into @Temp Values(1,7)
Insert Into @Temp Values(1,7)
Insert Into @Temp Values(1,12)
Insert Into @Temp Values(1,12)
Insert Into @Temp Values(1,17)
Insert Into @Temp Values(2,1)
Insert Into @Temp Values(2,1)
Insert Into @Temp Values(2,2)
Insert Into @Temp Values(2,4)
Insert Into @Temp Values(2,4)
The challenge is to write a query that calculates the Mode for each id. The output of this query should be...
[tt][blue]
Id Mode
----- ------
1 6
2 NULL
[/blue][/tt]
-George
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom