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

消除重复记录,解答者全分送
我现在要做一个查询语句(sqlserver)
主要目的要消除重复的注册号(EntRegNO)
现在数据库中有一个字段是日期型的AuthDate(取最大日期)
一个是状态标志EntStatusCode(只取=0的)
我用  
select   EntRegNO   ,max(AuthDate)   from   tdbase     where   EntStatusCode=0   group   by   EntRegNO       查出来的数据是201299条

select     EntRegNO,EntName,Addr,DistCode,LeRepName,CBuItem,BizMethod,EstDate,OpFromDate,OpToDate,LicExpDate,EntTypeCode,IndClassCode,Memo,RegCap,CurrencyCode   from   tdBase   T,(select   EntRegNO   E,max(AuthDate)   A   from   tdbase     where   EntStatusCode=0   group   by   EntRegNO)   B   where   T.EntStatusCode=0   and   T.AuthDate=B.A   and   T.EntRegNO=B.E   and   len(isnull(T.EntRegNO, ' '))> 0     order   by   T.EntRegNO

查出来的数据是201311条
怎么增加了12条?
现在不考虑结果
只考虑用分组出来的EntRegNO作为查询where条件过滤数据
如:select   *   from   tdbase   where   EntRegNO=group中的遍历
请高手赐   sql

------解决方案--------------------
同一注册号的日期有重复的吗?
select EntRegNO ,max(AuthDate) from tdbase where EntStatusCode=0 group by EntRegNO having count(distinct authdate) <> count(*)
如果能查到记录,说明有,你恐怕就得用其他的方法判断日期相同的记录哪一个是最后一条了,比如表中的自编号id
------解决方案--------------------
select * from tdbase a
inner join (select EntRegNO ,max(AuthDate) as Max_Date from tdbase where EntStatusCode=0 group by EntRegNO) b on a.EntRegNO = b.EntRegNO and a.AuthDate = b.Max_Date
------解决方案--------------------
select * from tdbase as A
where not exists(select 1 from tdbase where EntStatusCode=0 and EntRegNO=A.EntRegNO and AuthDate> A.AuthDate)

------解决方案--------------------
select EntRegNO,max(AuthDate),EntName,Addr,DistCode,LeRepName,CBuItem,BizMethod,EstDate,OpFromDate,OpToDate,LicExpDate,EntTypeCode,IndClassCode,Memo,RegCap,CurrencyCode from tdBase
where ...
group by EntRegNO,EntName,Addr,DistCode,LeRepName,CBuItem,BizMethod,EstDate,OpFromDate,OpToDate,LicExpDate,EntTypeCode,IndClassCode,Memo,RegCap,CurrencyCode
?
------解决方案--------------------
select * from tdbase a
inner join (select EntRegNO ,max(AuthDate) as Max_Date from (select distinct EntRegNO, AuthDate from tdbase where EntStatusCode=0) m group by EntRegNO) b on a.EntRegNO = b.EntRegNO and a.AuthDate = b.Max_Date

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

select a.* from tdbase a where a.AuthDate not in
(select max(b.AuthDate) from tdbase b where b.EntRegNO=a.EntRegNO)
and a.EntStatusCode = 0

------解决方案--------------------
怎么增加了12条?
T.AuthDate=B.A对应的记录不是唯一的,所以会多记录
------解决方案--------------------
select * from tdBase t
where AuthDate=(select max(AuthDate)--查询大的AuthDate
from tdbase where EntRegNO=t.EntRegNO)
------解决方案--------------------
因为有这样的数据:

EntRegNO AuthDate
001 1900-1-1 0:00:00
001 1900-1-1 0:00:00

这种数据当然会得到重复的记录.
------解决方案--------------------
里面数据其他字段可能有空值
------解决方案--------------------
分析一下,如果EntRegNO ,max(AuthDate)能够唯一确定一笔记录,那么就不需要再去取id;