我需要创建一个SQL查询来更新列中的值" position"通过按列" fruit"进行分组后,将整数值递增1。并按(ASC)排序"重量"。
示例:
从这张表开始:
id | fruit | weight | position
1 | Apple | 200 | 0
2 | Pear | 180 | 0
3 | Apple | 230 | 0
4 | Grape | 100 | 0
5 | Apple | 180 | 0
6 | Grape | 120 | 0
7 | Pear | 150 | 0
8 | Apple | 210 | 0
9 | Apple | 240 | 0
10 |Grape |90 | 0
11 |Pear |130 | 0
我想更新列"位置"并获得以下内容:
id | fruit | weight | position
5 | Apple | 180 | 1
1 | Apple | 200 | 2
8 | Apple | 210 | 3
3 | Apple | 230 | 4
9 | Apple | 240 | 5
10 | Grape | 90 | 1
4 | Grape | 100 | 2
6 | Grape | 120 | 3
11 | Pear | 130 | 1
7 | Pear | 150 | 2
2 | Pear | 180 | 3
列"位置"根据列"权重"增加整数值(从1开始)并通过" fruit"
进行分组答案 0 :(得分:1)
这可能很愚蠢,但您可以执行以下操作:
update teh_table t1
set position = 1 + (select count(*)
from teh_table t2
where t2.fruit = t1.fruit
and t2.weight < t1.weight);
即。对于每一行,计算具有相同果实但重量较轻的行数,然后加1。