Lets say I have a table of statisctics:
Page | Action | Time
--------------------
Home | Logon | 12
Home | Logon | 11
Home | Search | 20
About| Comment| 10
I can write a query to get the average Action time for each page:
select Page, avg(Time) from statistics group by Page
But I’d like to be a bit more clever. In order to highlight which pages have the most slow actions on, I’d like to get the sum of (time – average time for all actions on all pages). I could do this in separate queries:
select avg(Time) from statistics
-> 15
select Page, sum(Time - 15) from statistics group by Page
Question is, is there a way to do this in a single query?
Obviously select Page, sum(Time - avg(Time)) from statistics group by Page doesn’t work. Oracle throws “ORA-00937: not a single-group group function”.
You could use Window functions:
And to expand slightly you can then get many different averages in the one query:
http://sqlfiddle.com/#!4/42a5f/8