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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With