2014-11-06 4 views
0

처음에는 각 공급 업체가 각 고객에게 (배포자를 통해 간접적으로) 수행 한 총 달러 비즈니스의 내역을보고자했습니다. 여기에서 내부 조인 구문을 사용하지 않으려 고 시도하고 있습니다. 이 목적을 위해 아래 쿼리 :하위 쿼리 이해

select customers.cust_id, Vendors.vend_id, sum(quantity*item_price) as total_business from 
(((Vendors left outer join Products 
on Products.vend_id = Vendors.vend_id) 
left outer join OrderItems --No inner joins allowed 
on OrderItems.prod_id = Products.prod_id) 
left outer join Orders 
on Orders.order_num = OrderItems.order_num) 
left outer join Customers 
on Customers.cust_id = Orders.cust_id 
where Customers.cust_id is not null -- THE ONLY DIFFERENCE BETWEEN QUERY1 AND QUERY2 
group by Customers.cust_id, Vendors.vend_id 
order by total_business 

을 지금, 나는 거래에는 비즈니스 없었다 그 조합을 포함하여 모든 공급 업체 고객 조합에 대한 쿼리의 출력 결과를 확인하기 위해 노력하고 단일 SQL을 통해이 쓰기 위해 노력하고 있어요 질문. 저의 선생님은이 솔루션을 제공해 주셨지만 솔직히 말해서 서브 쿼리를 사용 해본 적이 없어서 논리를 전혀 이해할 수 없습니다.

select 
    customers.cust_id, 
    Vendors.vend_id, 
    sum(OrderItems.quantity*orderitems.item_price) 
    from 
     (
     customers 
     inner join 
     Vendors on 1 = 1 
    ) 
    left outer join --synthetic product using joins 
     (
     orders 
     join 
     orderitems on orders.order_num = OrderItems.order_num 
     join 
     Products on orderitems.prod_id = products.prod_id 
    ) on 
     Vendors.vend_id = Products.vend_id and 
     customers.cust_id = orders.cust_id 
group by customers.cust_id, vendors.vend_id 
order by customers.cust_id 

덕분에 많은

답변

0

나는이 쿼리를 작성합니다 구조는 매우 유사

select c.cust_id, v.vend_id, coalesce(cv.total, 0) 
fro Customers c cross join 
    Vendors v left outer join 
    (select o.cust_id, v.vend_id, sum(oi.quantity * oi.item_price) as total 
    from orders o join 
      orderitems oi 
      on o.order_num = oi.order_num join 
      Products p 
      on oi.prod_id = p.prod_id 
    group by o.cust_id, v.vend_id 
    ) cv 
    on cv.vend_id = v.vend_id and 
     cv.cust_id = c.cust_id 
order by c.cust_id; 

. 두 버전 모두 모든 고객과 공급 업체간에 교차 제품을 만들어 시작합니다. 이렇게하면 결과 결과 집합에 모든 행이 만들어집니다. 그런 다음이 수준에서 집계를 계산해야합니다. 위의 쿼리에서이 값은 고객/공급 업체 수준에 값을 집계하는 하위 쿼리로 명시 적으로 수행됩니다. (원래 쿼리에서 이것은 외부 쿼리에서 수행됩니다.)

마지막 단계는 이들을 결합하는 것입니다.

선생님은 테이블 별칭과 같은 테이블 별명을 사용하도록 권장해야합니다. 적절한 join을 사용하는 것이 좋습니다. 따라서 cross join을 과 on 1=1으로 표현할 수 있지만 cross join은 해킹이 아닌 SQL 언어의 일부입니다.

마찬가지로, from 절의 괄호를 사용하면 논리를 따라 가기가 더 어려워 질 수 있습니다. 명시 적 서브 쿼리는보다 쉽게 ​​읽을 수 있습니다.