sql - Incrementing Rank Value in Column -


i have table customers, products, , rank. each customer has 5 products:

customer, product, rank  cust a, product 3, 1  cust a, product 7, 2  cust a, product 6, 3  cust b, product 4, 1  cust b, product 6, 3  cust b, product 3, 5 

i removed of rows (like cust b rank 2 , 4).

how can go through table , wherever there break in rank (like missing 2 , 4) each customer , re-rank them (so 1,2,3 instead of 1,3,5)

first, don't have change data in table. use row_number() function when query:

select customer, product,        row_number() on (partition customer order rank) rank t; 

if use approach, don't have worry future deletions.

okay, if want change data, 1 method correlated subquery:

update t     set rank = (select count(*)                 t t2                 t2.customer = t.customer , t2.rank <= t.rank                ); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -