Skip to content
Advertisement

How to increment column by one group wise

I have a table called productLocation, and its data structure as follows, SQLFiddle

For each location have its own sorting order for products. But some of the products have 0 as the SortValue Now I need to write a query to update SortValue as,

If I consider one location, FkLocationId = 1

In the above data table, you can see, FkProductId = 100,101,102 have 0 as the SortValue. I need to update its sortValue as order by FkProductId descending order. I need to update its like

And also update the previous SortValue by one by one.

Then the complete output should be,

Is this possible to do? I’m really confused about this, please help me to solve this. Thank you

Updated:

Suppose I have another table as product. And its data structure as follows,

I also need to do same thing for this table as well, How can I do it

Expected Output:

Advertisement

Answer

Following is a sample query for you to check and use the same logic for your update process using CTE-

DEMO HERE

Important Note: Update is a risky process and you should try with your test data first.

Just use your “table_name” where I have used #temp

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement