Oracle Multiple update Query

前端 未结 1 1252
迷失自我
迷失自我 2021-01-25 23:30

I have two tables like the below one in my DB. In the first table ITEM for evry DEPARTMENT_CODE there will be multiple ITEM_CODE.

ITEM
-------------------------         


        
相关标签:
1条回答
  • 2021-01-25 23:49

    The following assumes that an ITEM_CODE is assigned to only one DEPARTMENT_CODE, because it's simple and you haven't given us any further business rules. It this assumption is wrong you will need to adjust the logic accordingly.

    I have also incorporated your requirement that the existing value of COMPETITOT.COMPETITOR_CODE is unreliable.

    Given this test date:

    SQL> select * from competitor
      2  /
    
    STORE_CODE  ITEM_CODE DEPARTMENT_CODE COMPETITOR
    ---------- ---------- --------------- ----------
            11     912003              14 01
            11     912003              14 04
            11     912003              14 03
            11     912004              14 01
            11     912004              14 02
            11     912004              14 04
            11     914001              14 01
            11     914001              14 02
            11     914001              14 05
    
    9 rows selected.
    
    SQL>
    

    We can use an analytic ROW_NUMBER() to generate the necessary handle for COMPETITOR_CODE:

    SQL> update competitor c
      2  set competitor_code =
      3          (select decode (dr
      4                         , 1, 'Comp_1'
      5                         , 2, 'Comp_2'
      6                         , 3, 'Comp_3')
      7             from ( select row_number() over ( partition by x.item_code
      8                                                  order by x.rowid ) as dr
      9                           , x.rowid as row_id
     10                    from competitor x
     11                    where x.item_code in ( select item_code
     12                                           from item
     13                                           where  department_code = 14 ) ) l
     14             where c.rowid = l.rowid )
     15  /
    
    9 rows updated.
    
    SQL>
    

    And this is the desired result (barring any further additions to the business rules):

    SQL> select * from competitor
      2  /
    
    STORE_CODE  ITEM_CODE DEPARTMENT_CODE COMPETITOR
    ---------- ---------- --------------- ----------
            11     912003              14 Comp_1
            11     912003              14 Comp_2
            11     912003              14 Comp_3
            11     912004              14 Comp_1
            11     912004              14 Comp_2
            11     912004              14 Comp_3
            11     914001              14 Comp_1
            11     914001              14 Comp_2
            11     914001              14 Comp_3
    
    9 rows selected.
    
    SQL>
    
    0 讨论(0)
提交回复
热议问题