Oracle删除连续重复项

时间:2018-03-19 10:00:48

标签: sql oracle oracle11g gaps-and-islands

我有一张表格,其中存储了客户的评估结果。评估可以多次触发。以下是样本数据

CUSTOMER_EVAL_RESULTS:
    SEQ    CUSTOMER_ID   STATUS   RESULT
    1       100           C        XYZ
    3       100           C        XYZ
    7       100           C        ABC
    8       100           C        PQR
    11      100           C        ABC
    12      100           C        ABC

从上面的数据集中我只想要SEQ为1,7,8,11的行。 我在其他链接上使用了以下查询建议,但它没有给出所需的结果。请帮忙

SELECT * FROM (
SELECT E.*, ROW_NUMBER() OVER(PARTITION BY CUSTOMER_ID, STATUS, RESULT ORDER BY SEQ) ROW_NUM 
FROM CUSTOMER_EVAL_RESULTS E WHERE E.CUSTOMER_ID=100
) WHERE ROW_NUM=1;

2 个答案:

答案 0 :(得分:3)

您可以使用LAG检查上一行的值:

SELECT * 
FROM
 (
   SELECT E.*,
      LAG(RESULT)
      OVER(PARTITION BY CUSTOMER_ID, STATUS
           ORDER BY SEQ) prevResult 
   FROM CUSTOMER_EVAL_RESULTS E 
   WHERE E.CUSTOMER_ID=100
) 
WHERE prevResult IS NULL
   OR prevResult <> RESULT

答案 1 :(得分:0)

请尝试以下

  select * from CUSTOMER_EVAL_RESULTS
  where not exists (select 1 from CUSTOMER_EVAL_RESULTS 
                    a,CUSTOMER_EVAL_RESULTS b
                    where a.seq_no < b.seq_no and a.customer_id=b.customer_id
                    and a.status=b.status and a.result=b.result     
                    and not exists(select 1 from CUSTOMER_EVAL_RESULTS c
                    where a.seq_no < c.seq_no and  c.seq_no < b.seq_no ));