I am struggling with a SQL query that I initially thought should be quite simple.
Imagine a table Users that uses a UserID as the PK and a column Age for the users age:
UserID Age
1 22
2 34
3 23
4 19
etc.
I’d like to be able to specify a UserID and return that user’s age as well as the average age of all other users. For example, if I specify UserID 1 then I’d like to see return set as:
UserID Age AvgAge
1 22 24.5
The following does not work: (as the WHERE is performed before GROUP BY)
Select UserID, Age, Avg(Age) as 'AvgAge'
From Users
Where UserID = 1
Group By UserId, Age
UserID Age AvgAge //Result set
1 22 22
Can anybody nudge me in the right direction?
By the way, in an ideal world the average age should not include the user that has been specified as the idea is to show their age relative to the average age of everybody else.
Given that there are 1000+ users then taking an average over all users will make no practical difference to the AvgAge number, though if anybody would like to show off their SQL prowess with a solution to that then I’d be interested to see it.
Thanks
Result: