table >>> sales
state | date | item | px
101 1/1/2012 tennis 2
101 1/1/2012 soccer 10
101 1/1/2012 crystal 100
101 1/1/2012 soccer 10
102 1/1/2012 crystal 100
102 1/1/2012 tennis 2
102 1/2/2012 tennis 2
103 1/2/2012 tennis 2
103 1/2/2012 crystal 100
103 1/3/2012 soccer 10
103 1/3/2012 crystal 100
$query="SELECT state, MAX(date), COUNT(state), AVG(px) FROM sales GROUP BY state ORDER by state ASC";
… produces:
state | date | item count | avg px
101 1/1/2012 4 30.5
102 1/2/2012 3 34.67
103 1/3/2012 4 53
Question: How can the query be modified to produce the average px of DISTINCT items in each state? (Instead of the average px of ALL items in each state)
E.g., the average for state 101 should/would be (2+10+100)/3 = 37.33; i.e., the average px for 1 tennis, 1 soccer and 1 crystal.
08-04-12 EDIT >>> Changed px column header in second table to avg px. / edited for clarity. thx.
Give this a try.
EDIT: Added an inner query to distinct based on the item and state.