2017-01-12 16 views
0

排序列數據我有3個字段的表:SQL - 表

CUST_ORDER FULFILL_NO ITEM LOCATION 
    SA23  1  0233 11001 
    SA23  1  0243 13001 
    SA23  1  0513 14001 
    SA88  1  0873 15001 
    SA88  1  0533 17001 

我想,這樣的數據變得測序fulfill_no領域:

CUST_ORDER FULFILL_NO ITEM LOCATION 
    SA23  1  0233 11001 
    SA23  2  0243 13001 
    SA23  3  0513 14001 
    SA88  1  0873 15001 
    SA88  2  0533 17001 

如何做到這一點?

+0

是否有您需要遵循的訂單?樣本數據不一致。 –

+0

不以任何順序。只是按照CUST_ORDER –

回答

5

您可以使用row_number()

select cust_order, 
     row_number() over (partition by cust_order order by location) as fulfill_no, 
     item, location 
from t; 

實際更新的數據可以在甲骨文棘手。這裏有一種方法:

update t 
    set fulfill_no = (select count(*) 
         from t t2 
         where t2.cust_order = t.cust_order and t2.location <= t.location 
        ); 
+0

的順序我需要更新該字段。 –

0

我想補充Gordon Linoff的答案。我想指出Gordon的row_number()解決方案可以在Microsoft SQL Server,Oracle和PostgreSQL中工作。考慮到問題中的oracle標籤,這個答案可能適用於提問者。

如果MySQL用戶發現此問題並需要解決方案,則應該使用會話變量。在MySQL實現ROW_NUMBER()被要求對已計算器:ROW_NUMBER() in MySQL 我很抱歉,我沒有的MySQL可用來測試,而是試圖在我的手定製上面查詢到MySQL ...

SELECT 
    t.CUST_ORDER, 
    (@rownum := @rownum + 1) AS FULFILL_NO, 
    t.ITEM, 
    t.LOCATION 
FROM YOUR_TABLE t, 
    (SELECT @rownum := 0) r 
ORDER BY t.CUST_ORDER, t.LOCATION 

更高級的用法,你可以試試這個鏈接。 http://www.mysqltutorial.org/mysql-row_number/