Oracle SQL Update使用group by / case

时间:2016-08-24 07:10:07

标签: sql oracle group-by

我有一个像

这样的结构的记录表1
KEY1 KEY2 KEY3 EMPLID ENRCD ADDL_SEQ ...

with (KEY1 KEY2 KEY3 EMPLID ENRCD ADDL_SEQ) being keys

我有EMPLID& ERNCD是相同但KEY1 / 2/3的不同值 当同一个EMPLID&存在多行时,我想将ADDL_SEQ值增加1。 ERNCD

例如

 - KEY1   KEY2 KEY3  EMPLID  ERNCD ADDL_SEQ
   001    A1   B1    12345   REG    1
   001    A1   B2    12345   REG    2

UPDATED SQL
UPDATE PS_XX_PY40_APAY_1 A1
SET A1.ADDL_SEQ =
(
    SELECT RANK() OVER(PARTITION BY XX_EMPLOYEE_ID,ERNCD ORDER BY 
    XX_CONVERSION_ID,XX_UCPATH_LOC,XX_WRKR_INSTANCE,XX_APPT_NUM,XX_DIST_NUM,EMPL_RCD,EMPLID,EFFDT)
    FROM PS_XX_PY40_APAY_1 B1
    WHERE B1.XX_EMPLOYEE_ID=A1.XX_EMPLOYEE_ID 
    and B1.ERNCD=A1.ERNCD
    AND XX_CONVERSION_ID=XX_CONVERSION_ID 
    AND XX_UCPATH_LOC=XX_UCPATH_LOC  
    AND A1.XX_WRKR_INSTANCE=B1.XX_WRKR_INSTANCE
    AND B1.XX_APPT_NUM=A1.XX_APPT_NUM  
    AND B1.XX_DIST_NUM=A1.XX_DIST_NUM  
    AND A1.EMPLID=B1.EMPLID  
    AND A1.EMPL_RCD=B1.EMPL_RCD 
    AND A1.EFFDT=B1.EFFDT
);

所有密钥都已加入的位置。但是,结果并不理想

结果

004720864   RGN 1
004720864   RGN 1
004720864   RGN 1
004720864   RGN 1

预期

   004720864    RGN 1
    004720864   RGN 2
    004720864   RGN 3
    004720864   RGN 4

3 个答案:

答案 0 :(得分:1)

这将产生您需要的编号

For Each cCell in Sheets(1).Range("$A$1:$A$95")
    Select Case cCell.Value
        Case "text1"
           Call text1Function
        Case "text2"
           Call text2Function
        'Do the rest that you need
    End Select
Next cCell

答案 1 :(得分:1)

您的update声明以及Tim回答中建议的问题是,他们没有考虑到rankrow_number分析函数在 之后计算 已经应用了where子句。因此,实际上,分析函数是在单行上计算的,显然总是返回1。绝对不是你想要的。

以下是使用适合您的merge语句执行更新的方法:

merge into table1 dest
using (
  select key1, key2, key3, emplid, enrcd,
         row_number() over (partition by emplid, enrcd
                                order by key1, key2, key3) as addl_seq
    from table1
) src
on (
  src.key1 = dest.key1
  and src.key2 = dest.key2
  and src.key3 = dest.key3
  and src.emplid = dest.emplid
  and src.enrcd = dest.enrcd
)
when matched then
  update set dest.addl_seq = src.addl_seq

答案 2 :(得分:0)

如果您只想选择编号,那么@Serg的答案应该没问题。如果要更新实际表,则以下内容应该有效:

UPDATE yourTable t1
SET t1.ADDL_SEQ =
(
    SELECT ROW_NUMBER() OVER(PARTITION BY EMPLID, ENRCD ORDER BY KEY1, KEY2, KEY3)
    FROM yourTable t2
    WHERE t2.EMPLID = t1.EMPLID AND
          t2.ENRCD  = t1.ENRDC AND
          t2.KEY1   = t1.KEY1 AND
          t2.KEY2   = t1.KEY2 AND
          t2.KEY3   = t1.KEY3
)

如果ADDL_SEQ列尚不存在,您可以通过以下方式创建:

ALTER TABLE yourTable ADD ADDL_SEQ int;