Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show the average and use it like condition in the same query?

I am working with a data base and I need to show the people who are older than the age average in a city comparing their age against that average. My code shows the people who is older than the average….but I can’t show the average of all the people (it’s allways the same number) in each line.

SELECT name, age FROM people
    WHERE age > (SELECT AVG(age) FROM people);

I need to show something like this:

name     age     average
Mick      18        17.5
Sarah     25        17.5
Joe       38        17.5

Any help, please.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can write the same subquery to calculate the average age within select list:

SELECT name, age, (SELECT AVG(age) FROM people) average FROM people
    WHERE age > (SELECT AVG(age) FROM people);

Or if your database allows window function you can do this:

select name,age,average from
(
  SELECT name, age, AVG(age) over() average FROM people
)t where age>average
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading