Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql query that groups different items into buckets

Tags:

sql

postgresql

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 i1        | 2 i2        | 12 i3        | 4 i4        | 16 i5        | 6 

output:

range   | number of item 0 - 10  |  3 10 - 20 |  2 

The way I am doing it so far is

SELECT count(*) FROM my_table Where price >=0 and price <10 

then

SELECT count(*) FROM my_table Where price >=10 and price <20 

and then copy pasting my results each time into excel.

Is there an automatic way to do this in an sql query?

like image 912
samuel_C Avatar asked Jul 12 '11 19:07

samuel_C


People also ask

Can you group by multiple things in SQL?

The SQL GROUP BY clause is used along with some aggregate functions to group columns that have the same values in different rows. The group by multiple columns technique is used to retrieve grouped column values from one or more tables of the database by considering more than one column as grouping criteria.

What is bucketing in SQL?

Bucketing, also known as binning, is useful to find groupings in continuous data (particularly numbers and time stamps). While it's often used to generate histograms, bucketing can also be used to group rows by business-defined rules.

How do you binning in SQL?

Binning, also known as discretization, is a way of putting similar data values into bins. We will accomplish this binning in T-SQL by using a CASE expression. In this tip, I have a table that contains 101,706 records. This table has an age column with age values from 0 to 100.

What is SQL Ntile function?

NTILE is an analytic function. It divides an ordered data set into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr . The expr value must resolve to a positive constant for each partition.


1 Answers

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.

like image 98
DRapp Avatar answered Oct 02 '22 23:10

DRapp