我有下面的查詢,我已經刪除了它的大部分,因爲有大約20個條件,它將只是太長和複雜的投入。我的查詢工作,我得到的數據是完全一樣,我想它是我的當年的數字和我以前的(數字)。這是通過前一年的一些子查詢來實現的,我從當前財政年度減去1。現在,當我的查詢變得更加複雜時,由於我擁有大量數據,我添加了其他15個子查詢,它有時可能需要超過12小時才能運行。有沒有更有效的方式來編寫這個查詢?如何讓我的查詢更高效?
編輯
不知道爲什麼,在一個完全有效的問題,這麼多downvotes。
SELECT
period,
finyear,
fin_week,
region,
store,
salesperson,
SUM(Fin_Revenue) as total_rev_ty,
SUM(CASE WHEN status_rev IN ('refund') THEN Fin_Revenue ELSE 0 END) as refund_rev_ty,
SUM(CASE WHEN status_rev IN ('credit') Fin_Revenue ELSE 0 END) as credit_rev_ty,
(
SELECT SUM(Fin_Revenue)
FROM [MYDB] r2
where r1.store = r2.store
AND r1.fin_week = r2.fin_week
AND r1.Salesperson = r2.Salesperson
AND r1.fin_yr = dateadd(yy,1,r2.fin_yr)
) as total_rev_ly,
(
SELECT SUM(CASE WHEN status_rev IN ('refund') THEN Fin_Revenue ELSE 0 END)
FROM [MYDB] r2
where r1.store = r2.store
AND r1.fin_week = r2.fin_week
AND r1.Salesperson = r2.Salesperson
AND r1.fin_yr = dateadd(yy,1,r2.fin_yr)
) as refund_rev_ly,
(SELECT
SUM(CASE WHEN status_rev IN ('credit') Fin_Revenue ELSE 0 END)
FROM [MYDB] r2
where r1.store = r2.store
AND r1.fin_week = r2.fin_week
AND r1.Salesperson = r2.Salesperson
AND r1.fin_yr = dateadd(yy,1,r2.fin_yr)
) as refund_rev_ly
FROM [MYDB] r1
WHERE
fin_yr IN ('2016')
包含'FROM'子句的實際上可能會鼓勵它運行。 –
@GordonLinoff,但它現在的方式是非常有效的!它非常及時地返回錯誤消息,並且不掃描任何表。 –
我很喜歡這種事情。 FROM語句現在在那裏。建設性的幫助可能比諷刺評論更好。謝謝。 – 80gm2