Skip to content
Advertisement

SQL: Conditional mean based on groups

Suppose I have a data like this

I want to calculate the average of VALUE by Group ID, but conditional on VALUE being smaller or equal than the median by group.

So for instance, for Group 1, the median is 4 and 2,3,4 are smaller or equal than 4, so it should give for group 1:

Does anyone have a clue how I can do this in Oracle/SQL?

Advertisement

Answer

You can calculate the median as an analytic function and then aggregate:

Note: You could filter using a where clause as well:

But the first method makes it simpler to add other expressions.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement