sql query that groups different items into buckets

前端 未结 3 827
梦毁少年i
梦毁少年i 2020-12-14 00:34

I am trying to write a query that returns the count of items whose price falls into certrain buckets:

For example if my table is:

item_name | price
i         


        
相关标签:
3条回答
  • 2020-12-14 01:18

    A bit of modification of DRapp's code...

    select
    case when price >= 0 and price < 10    then "  0 - 10"
               when price > 10 and price <= 50   then " 10+ - 50"
               when price > 50 and price <= 100  then " 50+ - 100"
               else "over 100"
    end As PriceRange,
    count(item_name) as ItemTotal
    from YourTable
    group by 
    case when price >= 0 and price < 10    then "  0 - 10"
               when price > 10 and price <= 50   then " 10+ - 50"
               when price > 50 and price <= 100  then " 50+ - 100"
               else "over 100"
    end;
    
    0 讨论(0)
  • 2020-12-14 01:26

    You can try grouping by 10 units of price:

    SELECT COUNT(*) AS tally,
           FLOOR(price/10) AS prange,
           CONCAT(10*FLOOR(price/10), "-", 10*FLOOR(price/10)+9) AS rstr
    FROM my_table
    GROUP BY prange;
    
    0 讨论(0)
  • 2020-12-14 01:35

    An expanded option from what Kerrek described, you can do you grouping based on a case/when

    select
          case when price >= 0 and price <= 10    then '  0 - 10'
               when price > 10 and price <= 50   then ' 10+ - 50'
               when price > 50 and price <= 100  then ' 50+ - 100'
               else 'over 100'
          end PriceRange,
          count(*) as TotalWithinRange
       from
          YourTable
       group by 1
    

    Here, the "group by 1" represents the ordinal column in your select statement... in this case, the case/when as TotalWithinRange.

    0 讨论(0)
提交回复
热议问题