SQL左连接以删除重复项

时间:2017-02-14 01:41:48

标签: sql join teradata

我有以下数据表:

表:

ID    Event
A     1
A     ?
B     ?

我想编写一个SQL查询,以便我可以删除重复的ID,而不是'?'上的实际值。我还可以保证唯一的重复项是针对具有常规事件(值为1-9)的ID以及“?”事件。所以在上面的例子中,我的查询应该返回:

ID  Event
A   1
B   ?

我希望我的查询返回与此描述匹配的行以及这些行的所有列。到目前为止,我的尝试是左连接:

sel L.*
from table L
left join table R
on L.ID = R.ID and
(L.Event is null and R.Event is not null)
where R.ID is null

这似乎部分奏效。它能够删除重复项,但不知何故,如果在上面的示例中存在非重复ID的情况,例如B带有'?'事件,则该行被删除。但是,还有其他情况保留相同的情况。

为什么会这样?我认为可能加入条件是正确的,因为我检查时间

R.Event is not null

但我的逻辑显然有些错误。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

有多种方法可以解决此问题,但left join只是没有想到。

这个怎么样?

select t.*
from t
where event <> '?'
union all
select t.*
from t
where event = '?' and
      not exists (select 1 from t t2 where t2.id = t.id and t2.event <> '?');

对于这些值,您还可以使用group by

select id, min(event)
from t
group by id;

但聚合不会保留行中的所有其他值。

或者,此类优先级查询的一般方法是row_number()

select t.*
from (select t.*,
             row_number() over (partition by id
                                order by (case when event = '?' then 1 else 2 end) desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;
相关问题