我被我的老闆給這個SQL查詢並告知要提高SQL Server查詢/優化它如何提高包含嵌套子查詢
DECLARE @pol_0 int, @pol_1 int, @pol_2 int, @pol_3 int, @pol_4 int, @pol_5plus int,
@peril_0 int, @peril_1 int, @peril_2 int, @peril_3 int, @peril_4 int, @peril_5plus int,
@loc_1 int, @loc_2_10 int, @loc_11_100 int, @loc_101_1000 int, @loc_1001_5000 int, @loc_5001plus int,
@locfass int, @polfass int, @pollim int, @polattpt int, @polded int, @maxded int, @polres int, @sublimit int,
@sitelim int, @siteded int, @SS int, @WX int, @QS int, @CAT int, @CORP int, @SL int,
@ty_port int, @ty_acct int, @ty_pol int, @ty_loc int,
@2mod_eq_0 int, @2mod_eq_1_10 int, @2mod_eq_11_20 int, @2mod_eq_21_27 int,
@2mod_hu_0 int, @2mod_hu_1_10 int, @2mod_hu_11_20 int, @2mod_hu_21_27 int
SELECT @pol_0 = COUNT(CASE CNT WHEN 0 THEN 99 ELSE NULL END),
@pol_1 = COUNT(CASE CNT WHEN 1 THEN 99 ELSE NULL END),
@pol_2 = COUNT(CASE CNT WHEN 2 THEN 99 ELSE NULL END),
@pol_3 = COUNT(CASE CNT WHEN 3 THEN 99 ELSE NULL END),
@pol_4 = COUNT(CASE CNT WHEN 4 THEN 99 ELSE NULL END),
@pol_5plus = COUNT(CASE WHEN CNT >= 5 THEN 99 ELSE NULL END)
FROM (SELECT ACCGRP.ACCGRPID,
COUNT(POLICYID) AS CNT
FROM ACCGRP
LEFT OUTER JOIN POLICY
ON ACCGRP.ACCGRPID = POLICY.ACCGRPID
GROUP BY ACCGRP.ACCGRPID
)
我的第一個想法就是放棄聲明和再轉換伯爵的成像
SELECT
(select COUNT(CASE CNT WHEN 0 THEN 99 ELSE NULL END),
(select COUNT(CASE CNT WHEN 1 THEN 99 ELSE NULL END),
(select COUNT(CASE CNT WHEN 2 THEN 99 ELSE NULL END),
(select COUNT(CASE CNT WHEN 3 THEN 99 ELSE NULL END),
(select COUNT(CASE CNT WHEN 4 THEN 99 ELSE NULL END),
(select COUNT(CASE CNT WHEN >= 5 THEN 99 ELSE NULL END) FROM
但FROM
條款有一個嵌套子查詢
FROM (SELECT ACCGRP.ACCGRPID, COUNT(POLICYID) AS CNT FROM ACCGRP LEFT OUTER JOIN POLICY ON ACCGRP.ACCGRPID = POLICY.ACCGRPID
GROUP BY ACCGRP.ACCGRPID)
我被某人的建議刪除嵌套的子查詢,但我不完全確定什麼是嵌套子查詢的更好的替代方案。任何建議將不勝感激!
+1 true - 首先測量,然後優化。也許只有一個索引缺失或某事,但查詢本身不是罪魁禍首。 – 2010-07-08 05:26:52