~/ 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/7b7cfc95-2de4-4a3f-a169-d9d0c457a60a/flashcard utf-8 LF