Reputation: 45
I realize this is an odd question, but I'd like to know if this is possible.
Let's say I have a DB with ages and IDs. I need to compare each ID's age to the average age, but I can't figure out how to do that without grouping or subqueries.
SELECT
ID,
AGE - AVG(AGE)
FROM
TABLE
I'm trying to get something like the above, but obviously that doesn't work because ID isn't grouped, but I group, then it calculates the average for each group, and not the table as a whole. How can I get a global average without a subquery?
Upvotes: 1
Views: 1560
Reputation: 48177
SELECT ID,
AGE -
AVG(AGE) OVER (partition by ID) as age_2
FROM Table
I just read is global avg
SELECT ID,
AGE -
AVG(AGE) OVER () as age_2
FROM Table
Upvotes: 2
Reputation: 1269533
The window logic for average age is:
SELECT ID, AGE - ( AVG(AGE) OVER () )
FROM TABLE;
You do not want ORDER BY
in the partitioning clause.
Upvotes: 1
Reputation: 1634
How can I get a global average without a subquery?
Use a variable.
DECLARE @AvgAge decimal(4,3)
SELECT @AvgAge = AVG(AGE) FROM TABLE
SELECT ID, AGE - @AvgAge [AgeDiff] FROM TABLE
Upvotes: 0