日期:2014-05-16  浏览次数:20690 次

查询重复记录,如:数据库为SQLSERVER2000
业务需求如下:查询表里的重复记录,取最新的一条数据:
建表语句:
CREATE TABLE clientlog (id int NOT NULL identity(1,1) PRIMARY KEY,
cimusername varchar(50) , 
username varchar(50) , 
password varchar(50) , 
defrayPassWord varchar(50) ,
tel varchar(50) ,  
updatecreatetime varchar(50) ,
createtime datetime default getDate(),
buyongyuanyin varchar(200) , 
cimQQ varchar(20), cimJSQQ varchar(20),  
cimName varchar(20), 
cimJSName varchar(20), 
state int, 
fukuan varchar(20),
YDprice decimal,
LTprice decimal ,
DXprice decimal);

以前用的是MYSQL数据库,现在需要把数据库从MYSQL换为SQLSERVER2000,MYSQL的写法为:
select * from 
(select * from clientLog order by id desc) as a 
where a.state = 1 group by a.username order by a.id desc
但在SQLSERVER2000上不能用。
我在SQLSERVER2000上的写法为:
select * from clientlog bb where exists(select 1 from (select max(username) as username,max(id) as id from clientlog) aa where aa.username=bb.username and aa.id=bb.id) and bb.state = 1
这样查询不出来数据,是不是没分组的原因。
请大家出出招.

------解决方案--------------------
SQL code
select *
from clientLog a
where not exists (select 1 from clientLog
    where username=a.username
    and id>a.id)
and state=1