2015-02-06 93 views
0

這裏是我當前的WIP查詢:過濾行與子查詢,如果列結果爲空

select 
    iclaim_id, 
    (select SUM(AuthAmtLineItems) as AuthAmt 
    from 
     (select 
       cauth_total as AuthAmtLineItems 
      from 
       claim_details_history 
      where 
       iclaim_id = cd.iclaim_id 
       and iclaim_det_status_id = 2 
       and btcovered_flag = 1 
      group by 
       irecord_id, sdetail_type, sdetail_desc, cauth_total) AuthAmt 
    having 
     SUM(AuthAmtLineItems) > 750) as AuthAmt 
from 
    claim_details_history cd 
where 
    iclaim_det_status_id = 2 
    and btcovered_flag = 1 
group by 
    iclaim_id 
having 
    min(dtupdate_last) between '02/05/2015 00:00:00.000' and '02/05/2015 23:59:59.997' 

這裏是結果集:

iclaim_id AuthAmt 
67712 3500.00 
71054 NULL 
71032 NULL 
71096 NULL 
68824 NULL 
71039 NULL 
71071 NULL 
67863 NULL 
71098 NULL 
70437 1500.00 
71048 NULL 
71037 NULL 
71080 NULL 
71035 NULL 
71049 NULL 
71118 NULL 
71053 759.14 

我所嘗試和失敗做的是刪除其中有NULL的行或having SUM(AuthAmtLineItems) > 750,無論哪個選項更容易。

回答

1

代替correlated subquery使用cross apply

SELECT iclaim_id, 
     AuthAmt 
FROM claim_details_history cd 
     CROSS apply (SELECT Sum(AuthAmtLineItems) AS AuthAmt 
        FROM (SELECT cauth_total AS AuthAmtLineItems 
          FROM claim_details_history 
          WHERE iclaim_id = cd.iclaim_id 
            AND iclaim_det_status_id = 2 
            AND btcovered_flag = 1 
          GROUP BY irecord_id, 
             sdetail_type, 
             sdetail_desc, 
             cauth_total) AuthAmt 
        HAVING Sum(AuthAmtLineItems) > 750) cs 
WHERE iclaim_det_status_id = 2 
     AND btcovered_flag = 1 
GROUP BY iclaim_id 
HAVING Min(dtupdate_last) BETWEEN '02/05/2015 00:00:00.000' AND '02/05/2015 23:59:59.997' 
+0

有什麼辦法,使這個走得更快?我的'相關的子查詢'在不到一秒的時間內運行,但是'交叉應用'花費了50秒的時間運行。它的工作原理!我必須在'GROUP BY'子句中添加'AuthAmt'。 – 2015-02-06 17:13:38