删除列值可能为null的重复记录

时间:2012-08-27 08:37:39

标签: oracle oracle11g

我的表有两列(CAGE,HCC)允许空值。我想在我的程序中显示重复记录,我这样写。

 FOR REC IN (SELECT LOCATION, NIIN, INVL_DATE, CAGE, 
          HCC,SUM(CA_QTY) AS SUM_CA,SUM(COST_QTY) AS  SUM_COST,COUNT(*) FROM INVENTORY 
          GROUP BY LOCATION, NIIN, INVL_DATE,
          CAGE, HCC 
          HAVING COUNT(*)>1)
 LOOP  
  VAR_LOC_NAME    :=  REC.LOCATION;
  VAR_NIIN        :=  REC.NIIN;
  VAR_DATE        :=  REC.INVL_DATE;
  VAR_CAGE        :=  REC.CAGE; 
  VAR_HCC         :=  REC.HCC;
  VAR_CA_QTY      :=  REC.SUM_CA;
  VAR_COST_QTY    :=  REC.SUM_COST;

 FOR REC1 IN (SELECT SNO FROM INVENTORY WHERE LOCATION=VAR_LOC_NAME AND  
                NIIN=VAR_NIIN AND TUNC(INVL_DATE)=TRUNC(TO_DATE(VAR_DATE,'DD-MM-YY'))  AND
                CAGE=VAR_CAGE AND HCC=VAR_HCC)
    LOOP
        DBMS_OUTPUT.PUT_LINE('GET NUMBER '||REC1.SNO);
    END LOOP;
   end loop;

但是对于CAGE和HCC的空值,它不起作用。 仅供参考:我正在使用oracle 11g

1 个答案:

答案 0 :(得分:0)

您需要找到一些未在CAGEHCC列中使用的值,并使用Oracle的NVL函数将NULL值替换为此唯一值。所以:

 FOR REC IN (SELECT LOCATION, NIIN, INVL_DATE, NVL(CAGE,-1) as CAGE, 
          NVL(HCC,-1) as HCC,SUM(CA_QTY) AS SUM_CA,SUM(COST_QTY) AS  SUM_COST,COUNT(*) FROM INVENTORY 
          GROUP BY LOCATION, NIIN, INVL_DATE,
          NVL(CAGE,-1), NVL(HCC,-1) 
          HAVING COUNT(*)>1)

当然-1只是一个示例。

关于第二个循环:

FOR REC1 IN (SELECT SNO FROM INVENTORY WHERE LOCATION=VAR_LOC_NAME AND  
            NIIN=VAR_NIIN AND TUNC(INVL_DATE)=TRUNC(TO_DATE(VAR_DATE,'DD-MM-YY'))  AND
            NVL(CAGE,-1)=VAR_CAGE AND NVL(HCC,-1)=VAR_HCC)

在打印输出时,您可以将-1替换为NULL