geoffroy
geoffroy

Reputation: 585

Distribution of values in a postgresql table

I have a Postgresql table like

user_name | product_name       
----------+-------------
      tom | candle
     bill | candle
     bill | candle
      tom | pen
     bill | pen

And I'd like to know the distribution of candle sales, i.e. how many people bought just one candle, how many people bought two candles, etc.

I have tried to use Postgreql window functions but my head hurts :) http://www.postgresql.org/docs/9.3/static/tutorial-window.html

Geoffroy

Upvotes: 1

Views: 2477

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125404

SQL Fiddle

select quantity, count(*)
from (
    select user_name, count(*) as quantity
    from t
    where product_name = 'candle'
    group by user_name
) s
group by quantity
order by quantity

Upvotes: 3

Related Questions