Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: get average for all values of a column for each distinct from another column

Tags:

sql

postgresql

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?

like image 678
Wes Avatar asked Oct 20 '25 14:10

Wes


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!