IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[Qsy_Xdjcb]') AND type = 'P')
DROP PROCEDURE [dbo].[Qsy_Xdjcb]
GO
-- =============================================
-- Author:<00384>
-- Create date: <2018-02-22>
-- Description:<关联行程计划显示巡店检查表情况>
-- =============================================
CREATE PROCEDURE [dbo].[Qsy_Xdjcb] 
-- Add the parameters for the stored procedure here
@startdate nvarchar(10),
@enddate nvarchar(10),
@zhouyi nvarchar(8)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
--declare @startdate nvarchar(10)
--declare @enddate nvarchar(10)
--declare @zhouyi nvarchar(8)

--set @startdate='2018-02-19'
--set @enddate='2018-02-19'
--set @zhouyi='20180219'
 
    
    if object_id('tempdb..#Txc') is not null
begin
drop table #Txc
end

create table #Txc(jb nvarchar(20),no nvarchar(20),name nvarchar(20),startdate date,enddate date,aim nvarchar(200),id int,cy int)

insert into #Txc
select *,row_number() over (order by jb,no,name,行程目的地,行程开始时间) as rowNum,null from (
    select sa.jb,sa.no,sa.name,xc.行程开始时间,xc.行程结束时间,xc.行程目的地  
    from (select distinct jb,no,name from Qsy_OldShopAdmin where ym=left(CONVERT(varchar(100), @zhouyi, 112),6)  ) sa 
    join (select distinct 主表ID,明细ID,业务单号,员工体系,建单部门,建单人工号,建单人,职级,开始日期,结束日期,上周总结,本周计划,行程类型,行程开始时间,行程结束时间,行程目的地,ord2_xcms 行程描述,行程状态  from Qsy_xcdk) xc on sa.no=rtrim(xc.建单人工号)
    join mps_job b on b.jb_ordtype='行程计划' and (b.jb_title='行程计划审核' or b.jb_title='部门领导审核') and b.jb_wsstatus!='返回至上一步' and xc.主表ID =b.jb_ordid 
    join  Qsy_oldshopinfo q on q.name=xc.行程目的地 and ym=left(CONVERT(varchar(100), @zhouyi, 112),6) 
    ) t
    
    update #Txc set cy=(select datediff(day,startdate ,t.enddate) from #Txc where id = t.id-1 and no=t.no and aim=t.aim) from #Txc t
    
    update #Txc set cy=(select 1 from #Txc where id = t.id+1 and no=t.no and aim=t.aim and t.cy is null) from #Txc t where t.cy is null
    
--select jb,no,name,aim,MIN(startdate) startdate,MAX(enddate) enddate from #Txc group by jb,no,name,aim,cy

select t.jb,t.no,t.name,'' 业务单号,'' 员工体系,'' 建单部门,'' 开始日期,'' 结束日期,'' 上周总结,'' 本周计划,'' 行程类型,t.startdate,t.enddate,t.aim,'' 行程描述,'' 提交时间,'' 通过时间,d.addtime,d.单据编号  
    from (select jb,no,name,aim,MIN(startdate) startdate,MAX(enddate) enddate from #Txc group by jb,no,name,aim,cy) t
    left join (select distinct no,shopname,addtime,单据编号 from xdjcb where 表单状态='已完成') d on t.aim=d.shopname and CONVERT(varchar(100),d.addtime, 23)>=t.startdate and CONVERT(varchar(100),d.addtime, 23)<=t.enddate and d.no=t.no 
    where t.startdate<=@startdate and t.enddate>=@enddate  
    order by d.addtime desc,t.jb,t.no,t.startdate


END