Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create number sequence based on two columns

I'm trying to generate number sequence based on 2 columns, Sno and UnitCost. The numbers should run down sequentially but they shouldn't change when both the columns are same. But if any one column is different it should increment.

I tried something with row_number(), rank(), dense_rank() but have been unable to hit the right logic.

Here's the required column and existing columns:

Sno    UnitCost   RequiredColumn
ch01   10         01
ch01   10         01
ch02   20         02
ch02   20         02
ch02   30         03
ch02   30         03
ch03   10         04

Any tips? Thanks.

like image 428
Mohammad Yusuf Avatar asked Mar 28 '26 23:03

Mohammad Yusuf


1 Answers

Using DENSE_RANK:

SELECT Sno, UnitCost, DENSE_RANK() OVER (ORDER BY Sno, UnitCost) RequiredColumn
FROM yourTable;
like image 101
Tim Biegeleisen Avatar answered Apr 01 '26 08:04

Tim Biegeleisen