3

I am trying to get the standard deviation from a table containing income values, using the basic math functions below in postgresql.

This is what I tried:

SELECT sqrt(sum(power(income - (sum(income) / count(income)), 2)) / (count(*) - 1)) FROM income_data

however, I keep getting the following error:

ERROR: aggregate function calls cannot be nested

Has anyone run into this issue? I feel like the logic for obtaining the standard deviation should work, although haven't had any luck thus far, I appreciate any suggestions on how to resolve.

2
  • 1
    Just use stddev(). No need to re-invent the wheel. Commented Jul 10, 2017 at 22:41
  • yes, I am aware stddev makes this easier, however, the idea is to use the basic math functions as the ones listed above and accomplish the same result as when using stddev Commented Jul 10, 2017 at 22:42

1 Answer 1

5

You should calculate a mean in a separate query, e.g. in a with statement:

with mean as (
    select sum(income) / count(income) as mean
    from income_data
)
select sqrt(sum(power(income - mean, 2)) / (count(*) - 1)) 
from income_data
cross join mean;

or in a derived table:

select sqrt(sum(power(income - mean, 2)) / (count(*) - 1)) 
from income_data
cross join (
    select sum(income) / count(income) as mean
    from income_data
) s;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.