日期:2014-05-18 浏览次数:20548 次
if object_id('[tb]') is not null drop table [tb] go create table [tb]([Name] varchar(1),[Status] varchar(4),[Data] datetime) insert [tb] select 'a','Pass','2012-05-12' union all select 'a','Pass','2012-05-11' union all select 'a','Fail','2012-05-09' union all select 'a','Pass','2012-05-10' union all select 'b','Pass','2012-05-12' union all select 'b','Fail','2012-05-11' union all select 'b','Pass','2012-05-10' union all select 'b','Pass','2012-05-09' union all select 'b','Pass','2012-05-08' union all select 'c','Pass','2012-05-09' union all select 'c','Pass','2012-05-12' union all select 'd','Pass','2012-05-09' union all select 'd','Pass','2012-05-08' union all select 'e','Pass','2012-05-12' union all select 'e','Pass','2012-05-11' union all select 'e','Pass','2012-05-09' union all select 'w','Pass','2012-05-12' union all select 'w','Fail','2012-05-12' union all select 'y','Pass','2012-05-12' union all select 'y','Fail','2012-05-11' union all select 'y','Fail','2012-05-09' union all select 'y','Fail','2012-05-06' union all select 'y','Fail','2012-05-05' union all select 'z','Fail','2012-05-06' union all select 'z','Fail','2012-05-05' go select name from ( select * from tb t where data in(select top 2 data from tb where name=t.name order by data desc) ) t where status='pass' group by name having count(1)>1 /** name ---- a c d e (4 行受影响) **/ select name from ( select * from tb t where data in(select top 2 data from tb where name=t.name order by data desc) ) t group by name having count(distinct status)>1 /** name ---- b w y (3 行受影响) **/
------解决方案--------------------
create table t1
(
name varchar(2),
sta varchar(5),
data date
)
insert into t1
select 'a','Pass','2012-05-12' union all
select 'a','Pass','2012-05-11' union all
select 'a','Fail','2012-05-09' union all
select 'a','Pass','2012-05-10' union all
select 'b','Pass','2012-05-12' union all
select 'b','Fail','2012-05-11' union all
select 'b','Pass','2012-05-10' union all
select 'b','Pass','2012-05-09' union all
select 'b','Pass','2012-05-08' union all
select 'c','Pass','2012-05-09' union all
select 'c','Pass','2012-05-12' union all
select 'd','Pass','2012-05-09' union all
select 'd','Pass','2012-05-08' union all
select 'e','Pass','2012-05-12' union all
select 'e','Pass','2012-05-11' union all
select 'e','Pass','2012-05-09' union all
select 'w','Pass','2012-05-12' union all
select 'w','Fail','2012-05-12' union all
select 'y','Pass','2012-05-12' union all
select 'y','Fail','2012-05-11' union all
select 'y','Fail','2012-05-09' union all
select 'y','Fail','2012-05-06' union all
select 'y','Fail','2012-05-05' union all
select 'z','Fail','2012-05-06' union all
select 'z','Fail','2012-05-05'
select * from t