Oracle - 基于列的表中的排序

时间:2017-04-09 09:25:31

标签: sql oracle

我有一个包含

列的表customer_order
ORD_ID, AI_LN, ITEM

数据就像

A100 null 001232
A100 null 108632
A100 null 501632
A200 null 301632
A200 null 601732

我需要根据订单编号AI_LN,因此它变为

A100 0 001232
A100 1 108632
A100 2 501632
A200 0 301632
A200 1 601732

怎么做?它会通过PLSQL块吗?

4 个答案:

答案 0 :(得分:1)

如果您只想选择给定的ai_ln,可以在选择中使用窗口函数:

select ord_id,
    row_number() over (
        partition by ord_id order by item
        ) - 1 as ai_ln,
    item
from your_table;

如果要使用它更新表,可以在合并语句中使用它。

merge into your_table t
using (
    select ord_id,
        row_number() over (
            partition by ord_id order by item
            ) - 1 as ai_ln,
        item
    from your_table
    ) s
    on (s.rowid = t.rowid)
when matched
    then
        update
        set t.ai_ln = s.ai_ln;

答案 1 :(得分:0)

不需要使用PL / SQL,这可以使用ROW_NUMBER分析函数在SQL中完成:

SELECT ORD_ID,
       ROW_NUMBER() OVER ( PARTITION BY ORD_ID
                           ORDER BY ITEM ) -- or ORDER BY ROWNUM
         AS ai_ln,
       ITEM
FROM   customer_order;

如果您想更新表格,请:

UPDATE customer_table c
SET ai_ln = (
  SELECT rn
  FROM   (
    SELECT ROW_NUMBER() OVER ( PARTITION BY ord_id
                               ORDER BY item )
             AS rn
    FROM   customer_table
  ) r
  WHERE c.ROWID = r.ROWID
);

MERGE

MERGE INTO customer_table dst
USING ( SELECT ROW_NUMBER() OVER ( PARTITION BY ord_id
                                   ORDER BY item ) AS rn
        FROM   customer_table ) src
ON ( dst.ROWID = src.ROWID )
WHEN MATCHED THEN
  UPDATE SET ai_ln = src.rn;

答案 2 :(得分:0)

使用row_number()分析函数:

select ORD_ID
     , row_number() over(partition by ORD_ID order by ITEM ) -1 as AI_LN
     , ITEM
  from table;

答案 3 :(得分:0)

您可以在不row_number()的情况下执行此操作:

update t
    set ai_ln = (select count(*) from t t2 where t2.ord_id = t.ord_id and t2.item <= t.item);

您可能希望在以下情况下使用此功能:

  • 您有(ord_id, item)的索引。
  • 订单没有重复项目。
  • 最大订单的商品数量有限(比如几十个)。