Re: SQL - histogram

From: Mathew White <innards(at)xmission(dot)com>
To: Txugo <msalt(at)uol(dot)com(dot)br>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: SQL - histogram
Date: 2001-07-11 04:39:01
Message-ID: Pine.LNX.4.33.0107102227380.9022-100000@innards
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

One way to do this is to use the 'CASE' expression, documented here:

http://pgsql.dbexperts.com.br/devel-corner/docs/postgres/functions-conditional.html

Because you have only one record per person, you can use the 'COUNT'
aggregate function to see how many of each height category match. An
example SQL statement for your height analysis would be:

SELECT CASE
WHEN height < 150 THEN '< 150'
WHEN height BETWEEN 150 AND 160 THEN '150 - 160'
WHEN height BETWEEN 160 AND 170 THEN '160 - 170'
WHEN height BETWEEN 170 AND 180 THEN '170 - 180'
WHEN height BETWEEN 180 AND 190 THEN '180 - 190'
WHEN height BETWEEN 190 AND 200 THEN '190 - 200'
ELSE '> 200' END AS category,
COUNT(*) AS qty
FROM person_table GROUP BY category;

On 9 Jul 2001, Txugo wrote:

> Hi,
> I've a problem as follow:
> I have a table where one record represent a person, including his height.
> I'd like to know how many person have more than 150 cm, more than 160 cm
> and so on.
> How can I do that using SQL?
>
> Example:
> people > 150 - 1000
> > 160 - 850
> > 170 - 500
> > 180 - 200
> > 190 - 30
> thanks in advance

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message David Stanaway 2001-07-11 05:30:29 cumulative sum in aggregate query.
Previous Message Robby Slaughter 2001-07-11 02:51:40 RE: "Display of specified number of records."