Please help me with a query to update a column value based on others grouped value. Thanks in advance.
Hard to explain so here is an example as I want to update Group value in this table:
Column:
[Id, Delivery, Food, Group]
Value:
[1, Ups, Vege, null]
[2, DHL, Vege, null]
[3, Ups, Meat, null]
[4, Ups, Vege, null]
[5, DHL, Mushroom, null]
[6, Fedex, Mushroom, null]
[7, Ups, Mushroom, null]
[8, Ups, Meat, null]
It’s like first group with Delivery then Group value will be incremental by grouped Food.
Expect to Group to be updated as:
[1, Ups, Vege, 1]
[2, DHL, Vege, 1]
[3, Ups, Meat, 2]
[4, Ups, Vege, 1]
[5, DHL, Mushroom, 2]
[6, Fedex, Mushroom, 1]
[7, Ups, Mushroom, 3]
[8, Ups, Meat, 2]
Seems mysql doesn’t support functions like DENSE_RANK(), so it’s quite inconvenient.
2
Answers
Please check my complete query
SELECT id, Delivery, Food, DENSE_RANK() OVER (PARTITION BY Delivery ORDER BY Delivery desc,food asc) AS GroupValue
FROM tb1 order by id
select statement can be used to update table.
the result wont be exact because in your expected order food is neither asc nor desc. if same output is needed then one more column needs to be added in which food order is to be specified. and the field need to be included in the above select statement in place of ‘food’