oracle查询根据条件删除重复行

时间:2015-08-09 08:51:43

标签: sql oracle join

我的数据如下表所示。

+------+----------+----------+
| type |  date1   |  date2   |
+------+----------+----------+
| IT1  | 05/01/15 | 08/01/15 |
| IT1  | 05/01/15 |          |
| IT1  | 04/01/15 |          |
| IT1  |          | 03/02/15 |
| IT1  | 06/01/15 | 03/02/15 |
| IT1  |          | 04/02/15 |
| IT2  | 05/01/15 |          |
| IT2  | 05/01/15 | 04/01/15 |
| IT2  | 03/01/15 |          |
| IT2  |          | 09/01/15 |
+------+----------+----------+

我需要通过删除重复项来获取行,结果在

下面
+------+----------+----------+
| type |  date1   |  date2   |
+------+----------+----------+
| IT1  | 05/01/15 | 08/01/15 |
| IT1  | 04/01/15 |          |
| IT1  | 06/01/15 | 03/02/15 |
| IT1  |          | 04/02/15 |
| IT2  | 05/01/15 | 04/01/15 |
| IT2  | 03/01/15 |          |
| IT2  |          | 09/01/15 |
+------+----------+----------+    

表示特定类型,

  1. 如果date1存在相应的date2,则选择该行并删除其他date1
  2. 如果相应的date2不存在则保留
  3. 类似地,

    1. 如果date2存在相应的date1,则选择该行并删除其他date2
    2. 如果相应的date1不存在则保留
    3. 是否可以为此编写oracle查询? 任何人都可以帮我这样做吗?

1 个答案:

答案 0 :(得分:1)

尝试此查询:

select *
from table1 t1
WHERE
  "date2" IS NOT NULL
  AND
  "date1" IS NOT NULL
  OR
  "date2" IS NULL 
  AND NOT EXISTS (
    SELECT 1 FROM table1 t2
    WHERE t1."type" = t2."type"
      AND t1."date1" = t2."date1"
      AND t2."date2" IS NOT NULL
   )
   OR
  "date1" IS NULL 
  AND NOT EXISTS(
    SELECT 1 FROM table1 t2
    WHERE t1."type" = t2."type"
      AND t1."date2" = t2."date2"
      AND t2."date1" IS NOT NULL
   )  

演示:http://sqlfiddle.com/#!4/12b8b/8