This week's giveaways are in the MongoDB and Jobs Discussion forums. We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line! See this thread and this one for details.
3. DISTRICT -------- STATE_ID DISTRICT_ID DISTRICT_NAME
4. CITY -------- DISTRICT_ID CITY_ID CITY_NAME POPULATION
I want to calcualte the avg population for the states in the country . In addition i would like to see the subtotal for State and Country.
select COUNTRY_NAME,STATE_NAME,avg(d.population) FROM COuntry a,State b,District c,City d where a.COUNTRY_ID=b.COUNTRY_ID and b.STATE_iD =c.STATE_iD and c.DISTRICT_ID=d.DISTRICT_ID group by COUNTRY_NAME,STATE_NAME
This is the most generalized aggregation clause. The general syntax is CUBE ( ). It is used with the GROUP BY only. CUBE creates a subtotal of all possible combinations of the set of column in its argument. Once we compute a CUBE on a set of dimension, we can get answer to all possible aggregation questions on those dimensions.
GROUP BY CUBE( a, b, c) is equivalent to
GROUP BY GROUPING SETS ( (a, b, c), (a, b), (b, c), (a, c), (a), (b), (c), ( )).
ROLLUP clause is used with GROUP BY to compute the aggregate at the hierarchy levels of a dimension.
ROLLUP(a, b, c) assumes that the hierarchy is "a" drilling down to "b" drilling down to "c".
ROLLUP (a, b, c) is equivalent to GROUPING SETS ( (a, b, c), (a, b), (a), ( )).
your problem is little tricky because you want to use two aggregate functions (sum & avg)in a single query therefore you may have to go for inner query.
you still didn't answer which database are you using ?