views:

249

answers:

3

Say I have a table of real estate properties:

A  15,000
B  50,000
C 100,000
D  25,000

I'd like to group them by 0 - 49,999, 50,000 - 99,999 and 100,000 - 200,000

So the result should be:

   0 -  49k (2)
 50k -  99k (1)
100k - 200k (1)

Is there a way to do that in one SQL statement? I'm using Postgres by the way.

+4  A: 

You can GROUP BY an experession, something like that:

SELECT price/50000*50000 AS minPrice, 
    (price/50000+1)*50000-1 AS maxPrice, 
    COUNT(*)
FROM table
GROUP BY price/50000;
Nicht Verstehen
I suppose you could even use CASE that tvanfosson mentioned in GROUP BY expression avoiding subqueries at the same time. Although you should measure what way performs better.
Nicht Verstehen
+1  A: 

Depends on whether you would accept a subselect in the statement and still call it one statement. Assuming that you want your ranges to extend, a subselect with a case statement to set the range, then an outer select grouping by range would work. If all of your ranges were the same size it would be easier as you could just divide by the range size and group by that.

select t.range, count(*) as num
from
   (select case
       when price < 50000 then '0 - 49K'
       when price >= 50000 and price < 100000 then '50 - 99K'
       when price >= 100000 and price < 200000 then '100 - 199K'
       ...
       as range,
       price
       from table) as t
group by range
tvanfosson
A: 

thanks all for help, unfortunately, the first one returns results that are not within bracket. The 2nd one does not work on postgres sql (apology that i forgot to mention my db.), however, the link that Captain Comic posted is the one that I tried and works perfectly.

once again thanks all.

David