Оптимизация Sql с помощью CTE и PIVOT
Может ли кто-нибудь помочь мне в том, как я могу оптимизировать свой запрос ниже.
Чтобы показать 50 тысяч записей, требуется больше минуты.
ТИА.
Что я уже пробовал:
Это мой вопрос.
with cte as ( select batch,lcoDt,runID,erpIO,style,article,leadtm,cfm_tag,EETA, asIO,planDt, class, pono,mainFab,matLeadTm,ExMillDt--, confirm_tag,special_range, order_qty, lpd_dt,req_del_cst ,ROW_NUMBER() over (partition by pono order by class) as seq from ( select distinct batch,lcoDt,runID,erpIO,style,article,leadtm,cfm_tag, (case when isnull(EETA,'')<>'' and isnull(ETA,'')<>'' then ETA else EETA end) 'EETA' ,asIO,planDt, class,pono,mainFab,matLeadTm,ExMillDt,-- confirm_tag,special_range, order_qty, lpd_dt,req_del_cst, ROW_NUMBER() over (partition by poNo,class order by eeta desc) as rowNumber from TableMatTrack where class != 'TRI' ) as maxDateResult where maxDateResult.rowNumber = 1 ) select batch 'Batch', lcoDt 'LCO Date', runID 'Run ID', asio 'AS400 IO#', erpIO 'ERP IO#', style 'Style ID', article 'Article', leadtm 'Gmt LT', pono 'Cust PONo', confirm_tag, special_range, order_qty, lpd_dt, req_del_cst, (dateadd(d,3,planDt)) 'PSDD Dt', class1_process, class1, class1_mainfab, class1_mat,class1_exMill,class1_eeta, class2_process, class2, class2_mainfab, class2_mat, class2_exMill,class2_eeta, class3_process, class3, class3_mainfab, class3_mat, class3_exMill,class3_eeta from ( select t.batch,t.lcoDt,t.runID,t.asIO,t.erpIO,t.style,t.article,t.leadtm, t.pono,t.cfm_tag, t.planDt,poDet.confirm_tag, poDet.special_range, poDet.order_qty, poDet.lpd_dt, poDet.req_del_cst, col = case when c.col = 'class' then col+cast(seq as varchar(10)) else 'class'+cast(seq as varchar(10))+'_'+col end, value from cte t left join (select distinct confirm_tag,special_range, order_qty, lpd_dt,req_del_cst,order_no,IO_no from TableBulkPO where Approve_tag=1 and upload_tag=1) as poDet on poDet.order_no= t.pono and poDet.IO_no= t.asIO cross apply ( select 'process', case when class = 'ACC' then 'SEW' when class = 'FAB' then 'CUT' else 'FN/PK' end 'Process' union all select 'class', class union all select 'mainfab', case when isnull(mainFab,'') <> '' then mainFab else 'N' end union all select 'mat', matLeadTm union all select 'exMill', case when isnull(ExMillDt,'') <> '' then convert(varchar(20),ExMillDt,101) else '' end as ExMillDt union all select 'eeta', case when isnull(EETA,'') <> '' then convert(varchar(20),EETA,101) else '' end as EETA ) c (col, value) ) d pivot ( max(value) for col in (class1_process, class1, class1_mainfab, class1_mat,class1_exMill,class1_eeta, class2_process, class2, class2_mainfab, class2_mat, class2_exMill,class2_eeta, class3_process, class3, class3_mainfab, class3_mat, class3_exMill,class3_eeta) ) piv;