当前位置: 代码迷 >> Sql Server >> -怎樣尋找出同一編號中最近一筆記錄裡的用戶和以前用戶不同的記錄解决方案
  详细解决方案

-怎樣尋找出同一編號中最近一筆記錄裡的用戶和以前用戶不同的記錄解决方案

热度:328   发布时间:2016-04-27 19:06:07.0
----------------------怎樣尋找出同一編號中最近一筆記錄裡的用戶和以前用戶不同的記錄
編號                               內容 用戶 時間
CZZ-0704033 1.xxx 11125237 2007/4/8   19:49
CZZ-0704033 1.xxyy 11125237 2007/4/9   19:50
CZZ-0704033 1,yyyy 11125237 2007/4/10   19:50
CZZ-0704033 1.zzzzz 11122845 2007/4/11   19:49
CZZ-0704034 .....


怎樣尋找出同一編號中最近一筆記錄裡的用戶和以前用戶不同的記錄,如上面的CZZ-0704033裡2007/4/11   19:49的用戶11122845就與這一編號的其它用戶不相同,請問怎樣查找出來。


謝謝!

------解决方案--------------------
select distinct 編號,用戶 from tb1 order by 編號
------解决方案--------------------
你是不是想找出一个编号,不同用户最后一次的记录呀,

可以这样

select * from 表 a
where not exists (select 1 from 表 where 編號=a.編號 and 用戶=a.用戶 and 時間> a.時間)
------解决方案--------------------
--最近紀錄
select 編號 ,max(時間) as 時間 from T group by 編號

"和以前用戶不同的記錄 ",這個理解有點吃力
------解决方案--------------------
--try看:

select A.*
from T A
inner join
(select 編號 ,max(時間) as 時間 from T
where (select count(distinct c.用戶) from T c where c.編號=T.編號) > 1
group by 編號) B
on A.編號=B.編號 and A.時間=B.時間

------解决方案--------------------
--创建测试环境
create table test
(
编号 varchar(30),
内容 varchar(30),
用户 varchar(30),
时间 datetime
)
insert into test select 'CZZ-0704033 ', '1.xxx ', '11125237 ', '2007/4/8 19:49 '
union all select 'CZZ-0704033 ', '1.xxyy ', '11125237 ', '2007/4/9 19:50 '
union all select 'CZZ-0704033 ', '1,yyyy ', '11125237 ', '2007/4/10 19:50 '
union all select 'CZZ-0704033 ', '1.zzzzz ', '11122845 ', '2007/4/11 19:49 '
union all select 'CZZ-0704034 ', '1.xxyy ', '11125239 ', '2007/4/9 19:50 '
union all select 'CZZ-0704034 ', '1,yyyy ', '11125239 ', '2007/4/10 19:50 '

--解决方法
select * from test a
where not exists(select 1 from test b where a.编号=b.编号 and a.时间 <b.时间)
and not exists(select 1 from (select * from test a
where not exists(select 1 from test b where a.编号=b.编号 and a.时间> b.时间)
) c where c.编号=a.编号 and c.用户=a.用户 )
  相关解决方案