IF OBJECT_ID('fr_xh') IS NOT NULL
DROP FUNCTION fr_xh
GO
CREATE FUNCTION dbo.fr_xh(@empid AS varchar(20))
RETURNS TABLE
AS
RETURN(
with a as (
select w.维修人员,convert(varchar(10),w.送修日期,23) 送修日期,w.维修单号,p.配件名称,p.设备编号,w.部门
from wxjld w
left join PJCKMXD p on w.维修单号=p.维修单号
where isnull(w.维修人员,'')<>'' and w.设备编号=@empid
group by w.维修人员,w.维修单号,w.送修日期,p.配件名称,p.设备编号,w.部门
)
, a1 as(
select *,row_number() over(PArtition by 维修人员,部门,设备编号,配件名称 order by 送修日期 desc) as xh from a
)
,a2 as(
select 部门,维修人员,维修单号,配件名称,设备编号,送修日期 as beginday,cast(送修日期 as varchar(10)) as endday,xh from a1
where xh=1
union all
select a.部门,a.维修人员,a.维修单号,a.配件名称,a.设备编号,a.送修日期,cast(b.beginday as varchar(10)) as endday,a.xh
from a1 a inner join a2 b on (a.xh=b.xh+1 and a.部门=b.部门 and a.设备编号=b.设备编号 and a.配件名称=b.配件名称)
where a.xh>1
)
, a3 as(
select distinct 配件名称,维修人员,设备编号,维修单号,beginday,endday,部门,1 val,datediff(day,beginday,endday) dd
from a2 a
where abs(datediff(day,beginday,endday)) between 0 and 7
)
select m.配件名称,b.维修单号,b.维修人员,b.设备编号,b.部门,b.beginday
from (
select a.配件名称,sum(a.val) val
from a3 a
group by a.配件名称
having sum(a.val)>1
) m
left join a3 b on m.配件名称=b.配件名称
)
GO
SELECT *
FROM PJCKMXD AS D CROSS APPLY fr_xh(D.设备编号) AS ST
WHERE D.设备编号=ST.设备编号 AND D.维修单号=ST.维修单号 AND D.配件名称=ST.配件名称
AND D.设备编号='QG30112'