Declare @pDLOI nvarchar(50);
Declare @pNLOI nvarchar(50);
set @pDLOI = 'Null,1,2,12,16,23' ;
set @pNLOI = '1';
SELECT distinct z.zone,t.assetid as assetid, z.window_open_offset, z.Indx into #tmp_recon
FROM tmp_SCH_VER_recon t left join dtv_zone_list z on t.zone = z.zone and t.sch_date >= z.sch_date_from and t.sch_date <=
z.sch_date_to join dtv_file_header h on h.id=t.file_id
where 1=1
and t.Sch_Date = '0319' and left(h.file_name, 4) = '2013'
and ( AssetID not like 'PH%' and ver_AssetID not like 'PH%' )
ORDER by z.Indx
select AssetID as assetid, sch_date, zone, Disposition_of_Loi, count(*) as VerCount into #tmp_dtl from tmp_sch_ver_recon t
join dtv_file_header h on h.id=t.file_id where 1=1 and ( ( left(h.file_name, 4) = '2013' and t.sch_date = '0319' ) )
and ( AssetID not like 'PH%' and ver_AssetID not like 'PH%' )
Group by AssetID,sch_date, zone, Disposition_of_LOI
order by zone, sch_Date
Declare @Nsqtr as nvarchar(2000);
set @Nsqtr = N'select d.zone, d.sch_date, d.assetid
, (select sum(t.VerCount) from #tmp_dtl t where t.zone=d.zone and t.assetid=d.assetid and t.Disposition_of_Loi in ( ' + @pNLOI + ') ) NLOI
, (select sum(t.VerCount) from #tmp_dtl t where t.zone=d.zone and t.assetid=d.assetid and t.Disposition_of_Loi in (' + @pDLOI + ') ) DLOI
from #tmp_recon r join #tmp_dtl d on r.zone = d.zone and r.assetid = d.assetid
group by d.zone, d.sch_date, d.assetid order by d.zone, d.sch_date, d.assetid '
EXECUTE sp_executesql @Nsqtr
drop table #tmp_recon
drop table #tmp_dtl