SQL: Finding averages and grouping by two parameters

46 views Asked by At
ID   Year   Month   Price
001  1990    JAN      6
001  1990    FEB      8
             ...
001  1990    DEC      4
001  1991    JAN      7
      ...
001  2000    DEC      6
002  1990    JAN      7
...

Given a table formatted like the one above, how can you find the average yearly price for each item (of each year)? So for example, I'd like to have a new table that looks like:

ID   Year   Avg_price
001  1990     7
001  1991     12
      ...
002  1990     11
...

I've tried the following code: SELECT ID, Year, AVG(Price) FROM DATA GROUP BY ID, Year

But end up getting 0 for each of the averages. The ordering seems to be working correctly though, so I'm not sure why this is. Any help would be greatly appreciated.

EDIT: It turns out there was nothing wrong with my SQL code at all. I guess the answer was simply a bug. Thanks for all your replies, everyone.

1

There are 1 answers

0
Fabian Bigler On

Your SQL looks fine to me (Checked with MS SQL).

SQL Fiddle Demo

Please doublecheck with MySQL. ;-)