'How to segregate data into groups based on the value in sql?

I have a table in the below format:

Pan_no ANA_Code R_units R_price absolute_returns
BBJ Equity 1.5 500 15000
AAX Debt 2.0 1500 3000
EDF Debt 3.0 500 -91

Like the above sample data i have 10,000,000 records available. Now I require another column were i need to divide absolute_returns columns into bins(groups) and put them into 5 buckets based on the values like 1,2,3,4,5 then i need to find sum(r_price),sum(r_units) which is then grouped by pan_no, ana_code, and bins(this bins is the new column that will be created).

I tried to achieve the above with the below code:

select 
    pan_no, ana_code, 
    sum(r_units), sum(r_price),
    ntile(5) over (order by absolute_returns) as bins 
from 
    table1 
group by 
    pan_no, ana_code, bins;

What am I missing in my code? I am just trying to create 5 bins for absolute_returns column and then summing up the r_price and r_units and then trying to group the data by pan_no, ana_code and bins. But the code doesn't work.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source