日期:2014-05-18  浏览次数:20514 次

如何返回多字段重复的完整记录集
id a b c d
1 zh tec 21 null
2 ze tec 32 bb
3 ze tec 37 null
4 ze tec 37 cc
5 ze te 22 bb
6 zh tec 21 cc
7 zh te 32 null

id为标识列。
1. 查询:要找出列a,b都相同的完整记录集(后面需要判断列c和列d):
id a b c d
1 zh tec 21 null
6 zh tec 21 cc
2 ze tec 32 bb
3 ze tec 37 null
4 ze tec 37 cc

2. 删除:对于列a,b都相同的记录,只保留列d不为空值且id最大的记录,即删除以下记录:
id a b c d
1 zh tec 21 null
2 ze tec 32 bb
3 ze tec 37 null

------解决方案--------------------

delete from T
where id in(
select id from T t
where d is null and
exists(select 1 from T
where t.a = a and t.b = b and t.id > id))
------解决方案--------------------
SQL code


select   *   from   tb   as   m,
(
select   a   ,b
from   tb
group   by   a   ,   b
having   count(*)> 1
)n
where   m.a   =   n.a   and   m.b   =   n.b

------解决方案--------------------
探讨

非常感谢,我就是想要这种方法,好好学习一下。如果还要判定非重复字段a和d呢?如m.a>n.a, m.d<>n.d,子查询里不能select a,d吧,肿么办?
引用:
SQL code
select * from tb as m,
(
select a ,b
from tb
group by a , b
havin……

------解决方案--------------------
SQL code

问题2删除:

delete t1 from tb t1 where exists(select 1 from tb t2 where t2.d is not null and t1.a =t2.a and t1.b =t2.b and t1.id<t2.id)