-1

I'm new at SQL and having a problem about calculating averages in my SQL database. I have two columns (ID which is unique for that table and price for every ID), and I need to calculate averages for every ID individually. My table looks something like this:

ID        PRICE   
---------------
1.         500
1.         700
1.         840
1.         790
1.         800
2.        1500
2.        1480
2.        1620
2.        1700
2.        1560

(have much more ID numbers, but I'm guessing the solution is the same no matter how many ID is there, if there is a solution).

When I try to calculate average, it takes all values from PRICE column, but I need to calculate average for ID 1, ID 2, ID 3, ID 4…. individually, for later calculations. I tried to find the answer online, but I failed. Is it even possible to calculate that way averages or I need another approach?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Possible duplicate of [Average of grouped rows in Sql Server](http://stackoverflow.com/questions/3100921/average-of-grouped-rows-in-sql-server) – Dan Getz Dec 04 '16 at 20:03

2 Answers2

1

That would be something like

SELECT ID, AVG(PRICE)
FROM SomeTable
GROUP BY ID;
0

I'm not sure how your data is structured. You're description suggest no average needed. If you indeed have two columns: id, price and id is unique then simple

SELECT id, price FROM table_name

will give you averages, because there could be only one price per every (unique) id.

But then your question doesn't make sense. So suppose id is not unique, and there might be few rows with same id and different prices. In that case you need a GROUP BY clause.

SELECT id, avg(price) as avg_price FROM table_name GROUP BY id
Konrad Perzyna
  • 231
  • 3
  • 4