group by price range

后端 未结 2 1683
半阙折子戏
半阙折子戏 2021-01-12 16:33

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,99

相关标签:
2条回答
  • 2021-01-12 16:40

    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;
    
    0 讨论(0)
  • 2021-01-12 16:47

    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'
           ...
           end
           as range,
           price
           from table) as t
    group by range
    
    0 讨论(0)
提交回复
热议问题