declare @tb table
(
  客户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 '与上次的间隔日期'
       ,(case when t.维修日期=(select min(维修日期) from @tb where 客户id=t.客户id)
              then null
              else t.客户id
         end
        ) as '上次的客户id'
      ,(select top 1 主板sn号 
            from @tb 
                where 维修日期=(select max(维修日期) 
                                  from @tb 
                                      where 维修日期<t.维修日期
                                            and 客户id=t.客户id)
                      and 客户id=t.客户id
       ) as '上次sn号'
       ,(select top 1 换新的主板sn号 
            from @tb 
                where 维修日期=(select max(维修日期) 
                                  from @tb 
                                      where 维修日期<t.维修日期
                                            and 客户id=t.客户id)
                      and 客户id=t.客户id
       ) as '上次新sn号'
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号)

解决方案 »

  1.   

    我的意思能不能用个 left join
      

  2.   

    我的意思能不能用个 left join 把上次的记录取出来
      

  3.   

    select a.客户id,a.主板sn号,a.换新的主板sn号,a.维修日期,上次的间隔日期=isnull(datediff(d,b.维修日期,a.维修日期),0) ,上次客户id=b.客户id,上次sn号=b.主板sn号
    ,新sn号=b.换新的主板sn号
    from #2 a
    left join #2 b
      on b.客户id=a.客户id and b.维修日期=(select max(维修日期) from #2 where 客户id=a.客户id and  维修日期<a.维修日期 )
    --其中#2代表你要用到的表名