您好,登錄后才能下訂單哦!
實(shí)現(xiàn)把full join改為left join +union all?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
一、原始語(yǔ)句如下:
select isnull(vv.customer_id,v.customer_id) as customer_id, isnull(vv.business_date,replace(v.business_date,'-','')) as business_date, v.prod_id, v.sales, vv.visit_count, v.all_sales from ( SELECT a.customer_id , max(month)+'-01' as business_date, a.PROD_ID , SUM(CAST(VALUE AS NUMERIC(38, 3))) sales, sum(SUM(CAST(VALUE AS NUMERIC(38, 3)))) over(partition by a.customer_id) as all_sales FROM TB_IMPORT_SALES a WHERE a.customer_id IS NOT NULL AND a.PROD_ID IS NOT NULL and a.month='2016-11' GROUP BY a.customer_id , a.PROD_ID )v full join ( SELECT customer_id, max(a.business_date) as business_date, COUNT(*) AS VISIT_COUNT FROM TB_CALL_STORE a WITH(NOLOCK) inner join TB_TIME d on a.business_date = d.t_date where d.section ='2016-11' GROUP BY customer_id )vv on v.customer_id = vv.customer_id
原來(lái)是left join,雖然查詢(xún)比較慢,但是2分鐘能查出來(lái),現(xiàn)在按照業(yè)務(wù)要求,需要看到所有數(shù)據(jù),所以改成了full join,改了之后5分鐘都查不出結(jié)果。
二、改寫(xiě)后的代碼
select v.customer_id, replace(max(v.business_date),'-','') as business_date, v.prod_id, max(v.sales_volume) sales_volume , max(v.visit_count) visit_count, max(v.all_sales_volume) all_sales_volume from ( SELECT a.customer_id , max(biz_month)+'-01' as business_date, a.PROD_ID , SUM(CAST(VALUE1 AS NUMERIC(38, 8))) sales_volume, sum(SUM(CAST(VALUE1 AS NUMERIC(38, 8)))) over(partition by a.customer_id) as all_sales_volume, null as visit_count FROM TB_IMPORT_SALES a WHERE a.customer_id IS NOT NULL AND a.PROD_ID IS NOT NULL and a.month='2016-11' GROUP BY a.customer_id , a.PROD_ID union all SELECT customer_id, max(a.business_date) as business_date, p.prod_id, null, null, COUNT(*) AS VISIT_COUNT FROM TB_CALL_STORE a WITH(NOLOCK) cross apply ( select top 1 prod_id from TB_PRODUCT with(nolock) )p inner join TB_TIME d on a.business_date = d.t_date where d.section ='2016-11' GROUP BY customer_id,p.prod_id )v group by v.customer_id, v.prod_id
由于代碼本身比較簡(jiǎn)單,沒(méi)辦法再進(jìn)一步簡(jiǎn)化,而由于連接不了服務(wù)器,其他的方法也用不上,甚至沒(méi)辦法分析到底是什么導(dǎo)致運(yùn)行這么慢。
想了想,full join 本質(zhì)上就是 2次left join+union ,無(wú)非就是合并數(shù)據(jù),于是嘗試一下用union all來(lái)直接合并數(shù)據(jù),現(xiàn)在改成unoin all最后,就不需要full join。
但是考慮到第2段代碼中并沒(méi)有prod_id這個(gè)字段,所以這里在第2段代碼加上了cross apply隨便取出一個(gè)產(chǎn)品的id,這樣就有prod_id這個(gè)字段,可以合并了。
修改之后,果然速度降到了10多秒。
看完上述內(nèi)容,你們掌握實(shí)現(xiàn)把full join改為left join +union all的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。