Oracle - 更新,解码和设置值

时间:2013-04-09 14:15:56

标签: sql database oracle oracle10g

我有一张桌子,例如

**Fruit   Number**
Apple     5
Grape     9
Orange    1
Coconut   54
Mango     22

我想:

  1. 选择整个列表
  2. 将'Apple,Mango,Coconut'放在首位。
  3. 更新当前订单,其中number = rownum
  4. 该列表应如下所示:

    **Fruit   Number**
    Apple     1
    Mango     2
    Coconut   3
    Grape     4
    Orange    5
    

    我尝试了以下但是遇到语法问题..

    update tablename 
    set id = rownum
    where fruit in (select fruit from table order by decode(fruit,'Apple',1,'Mango',2,'Coconut',3))
    

2 个答案:

答案 0 :(得分:0)

UPDATE (
    SELECT ROWNUM+5 AS r, fruit, number FROM TABLE
    WHERE fruit NOT IN ('Apple', 'Mango', 'Coconut', 'Grape', 'Orange')
    UNION
    SELECT 1 AS r, 'Apple' AS fruit, number FROM TABLE
    UNION
    SELECT 2 AS r, 'Mango' AS fruit, number FROM TABLE
    UNION
    SELECT 3 AS r, 'Coconut' AS fruit, number FROM TABLE
    UNION
    SELECT 4 AS r, 'Grape' AS fruit, number FROM TABLE
    UNION
    SELECT 5 AS r, 'Orange' AS fruit, number FROM TABLE
) 
SET number = r;

答案 1 :(得分:0)

以下查询将为您完成。

UPDATE table SET number =
CASE fruit
    WHEN 'Apple' THEN 1
    WHEN 'Mango' THEN 2
    WHEN 'Coconut' THEN 3
    WHEN 'Grape' THEN 4
    WHEN 'Orange' THEN 5
END;