Postgres: get average for all values of a column for each distinct from another column
postgresql, sql
Solution
That's precisely what `group by` is for:
SELECT sku, AVG(qty)
FROM the_table
GROUP BY sku;
The manual has some examples: http://www.postgresql.org/docs/current/static/queries-table-expressions.html#QUERIES-GROUP
Problem
I have a table that looks like: ``` sku | qty ----|---- sku1| 1 sku1| 3 sku1| 1 sku1| 3 sku2| 1 ``` And I'm trying to write a query that will return the average of `qty` for each distinct `sku`. So for the data above, the output from the query would look like: ``` sku | qty ----|---- sku1| 2 sku2| 1 ``` So, the averages for `sku1` came from `1 3 1 3` and the average of `sku2` is just `1` I know it's going to involve some kind of subquery, but I just can't seem to figure it out. ``` SELECT sku, AVG(qty) FROM (SELECT DISTINCT sku FROM table) ``` How do I query for the average qty for each sku?