2012-04-30 3 views
6

왼쪽 외부 조인에 대한 case 문을 사용하여이 SQL 문을 최적화 할 수 있다고 생각합니다.SQL 최적화 사례 문

하지만 저는 AB, CD 및 다른 모든 코드 유형을 요약하기 위해 사례를 설정하는 데 어려움을 겪고 있습니다.

저에게 줄 수있는 도움이나 조언을 보내 주시면 감사하겠습니다.

update billing set payments = isnull(bd1.amount, payments) 
, payments = case 
     when payments is null then 0 
     else payments 
    end 
, charges = case 
     when bd2.amount is not null then charges 
     when charges is null then 0 
     else charges 
     end 
, balance = round(charges + isnull(bd1.amount, bi.payments), 2) 
from billing bi 

left outer join (select inv, round(sum(bd1.bal), 2) amount 
       from "bill" bd1 
       where code_type = 'AB' 
       or code_type = 'CD' 
       group by inv) bd1 
       on bd1.inv = bi.inv 
left outer join (select invoice, round(sum(bd2.bal), 2) amount 
       from "bill" bd2 
       where code_type <> 'AB' 
       and code_type <> 'CD' 
       group by inv) bd2 
       on bd2.inv = bi.inv; 
+3

유효합니까? 'payments' 칼럼을 두 번 업데이트하는 것 같습니다. –

+0

@ 시바 나는 이점 9를 사용하고 있습니다 – Trevor

답변

5

2 개가 아닌 단일 쿼리를 사용하여이 작업을 단순화 할 수 있습니다. UPDATE의 GROUP BY가 작동하지 않기 때문에 여전히 하나가 필요합니다.

UPDATE bi 
SET payments = bd.payments, 
     charges= bd.charges, 
     balance = bd.balance 
FROM billing bi 
     LEFT JOIN (SELECT bd.inv, 
         payments = Round(Sum(CASE 
               WHEN code_type IN ('AB' , 'CD') THEN 
               bd.bal 
               ELSE 0 
               END), 2), 
         charges = Round(Sum(CASE 
               WHEN code_type NOT IN ('AB' , 'CD') THEN 
               bd.bal 
               ELSE 0 
              END), 2), 
         balance = Round(Sum(bd.bal), 2) 
        FROM bill bd 
        GROUP BY bd.inv) bd 
     ON bd.inv = bi.inv 
+0

이것은 유효한 구문이 아닙니다. 집합 목록에는 집계 함수를 직접 사용할 수 없습니다. – GarethD

+0

@GarethD 그래, 내가 그것을 고쳤다, 마지막으로 편집을 참조하십시오. –

+0

그래, 미안하지만, 내가 100 % 확신 할 수 없다는 것을 확인했다. 그래서 내가 실제로 게시했을 때 이미 그것을 고쳤다. . 'Code_Type = 'AB'또는 Code_Type = 'CD'' 대신에'CASE WHEN Code_Type IN ('AB ','CD ')를 사용하여 이것을 더 향상시킬 수 있습니다. – GarethD

1

아마 이런 일이 :

update billing set payments = isnull(bd1.amount, payments) 
, payments = isnull(payments, 0) 
, charges = isnull(bd2.amount, isnull(charges, 0)) 
, balance = round(charges + isnull(bd1.amount, bi.payments), 2) 
from billing bi 

left outer join (select inv, round(sum(bd1.bal), 2) amount 
       from "bill" bd1 
       where code_type in ('AB', 'CD') 
       group by inv) bd1 
       on bd1.inv = bi.inv 
left outer join (select invoice, round(sum(bd2.bal), 2) amount 
       from "bill" bd2 
       where code_type not in ('AB', 'CD') 
       group by inv) bd2 
       on bd2.inv = bi.inv; 

두 왼쪽은 문제가되지 않습니다 조인!