1.select * from 表 t
where (select count(1) from 表 where 主板sn号=t.主板sn号)>1
or
exists(select 1 from 表 where 主板sn号=t.换新的主板sn号)
or
exists(select 1 from 表 where 换新的主板sn号=t.主板sn号)
where (select count(1) from 表 where 主板sn号=t.主板sn号)>1
or
exists(select 1 from 表 where 主板sn号=t.换新的主板sn号)
or
exists(select 1 from 表 where 换新的主板sn号=t.主板sn号)
与上次的间隔日期
与上次的间隔日期 怎么算 ?
(
客户id int,
主板sn号 varchar(10),
换新的主板sn号 varchar(10),
维修日期 datetime
)
insert @tb
select 1,'a','b','2004-1-2' union
select 1,'b','c','2004-1-3' union
select 1,'c','d','2004-1-5' union
select 2,'ddd','6666','2005-4-5' union
select 2,'eee',null,'2005-4-5' union
select 3,'3a',null,'2005-4-5' union
select 3,'3a',null,'2005-4-8'--查询重复修理清单
select *
,isnull(datediff(day
,(select max(维修日期)
from @tb
where 维修日期<t.维修日期
and 客户id=t.客户id)
,t.维修日期
),0) as '与上次的间隔日期'
from @tb t
where (select count(1) from @tb where 主板sn号=t.主板sn号)>1
or
exists(select 1 from @tb where 主板sn号=t.换新的主板sn号)
or
exists(select 1 from @tb where 换新的主板sn号=t.主板sn号)
--结果
/*客户id 主板sn号 换新的主板sn号 维修日期 与上次的间隔日期
----------- ---------- ---------- ---------------------------------------------
1 a b 2004-01-02 00:00:00.000 0
1 b c 2004-01-03 00:00:00.000 1
1 c d 2004-01-05 00:00:00.000 2
3 3a NULL 2005-04-05 00:00:00.000 0
3 3a NULL 2005-04-08 00:00:00.000 3(所影响的行数为 5 行)
*/select identity(int,1,1) id,*
into #
from @tb t
where (select count(1) from @tb where 主板sn号=t.主板sn号)>1
or
exists(select 1 from @tb where 主板sn号=t.换新的主板sn号)
or
exists(select 1 from @tb where 换新的主板sn号=t.主板sn号)order by 客户id,维修日期select t.客户id
,count(1)-1 as '总重复修理件数'
,sum(case when datediff(day,tb.维修日期,t.维修日期)=1
then 1
else 0
end
) as '与上次的为1天件数'
,sum(case when datediff(day,tb.维修日期,t.维修日期)=2
then 1
else 0
end
) as '与上次的为2天件数'
,sum(case when datediff(day,tb.维修日期,t.维修日期)=3
then 1
else 0
end
) as '与上次的为3天件数'
from # t
left join (
select id,客户id
,维修日期
from #
)tb on t.客户id=tb.客户id and t.id-1=tb.id
group by t.客户iddrop table #--结果
/*
客户id 总重复修理件数 与上次的为1天件数 与上次的为2天件数 与上次的为3天件数
----------- ----------- ----------- ----------- -----------
1 2 1 1 0
3 1 0 0 1(所影响的行数为 2 行)
*/