~/ learn/ postgresql/ cards/ string_agg, FILTER & friends
1 of 2

Per genre, show the count (n), average price to 2 dp (avg_price), and how many are out of stock (out_of_stock) — use FILTER.

Per genre, show the count (n), average price to 2 dp (avg_price), and how many are out of stock (out_of_stock) — use FILTER.

Answer

SELECT genre, count(*) AS n, round(avg(price), 2) AS avg_price, count(*) FILTER (WHERE stock = 0) AS out_of_stock FROM books GROUP BY genre;

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/7bc9938f-4c41-4a71-8b9f-bd20fbe13c43/flashcard utf-8 LF