2016-06-01 2 views
1

각 상점의 제품 수/시스템 수를 찾으려고합니다. 표는 다음과 같다 :테이블을 조인 한 후 원래 수를 얻는 방법은 무엇입니까?

Store 
Id 
100 
200 

Customer 
Id  | dealerId 
1  | 100 
2  | 200 

System 
Id | CustomerId 
20 | 2 
30 | 2 
40 | 2 
50 | 1 

Product 
Id | SystemId 
1000 | 20 
2000 | 50 

나는 얻기 위해 노력하고 있어요 :

storeId | Number of systems | number of products | average 
100  |   1  |   1   |  1/1 
200  |   3  |   1   |  1/3  

내가이 쿼리를 작성했습니다. 적절한 수의 제품을 얻지 만 시스템 수는 내가 테이블에 합류하기 때문에 엉망입니다. 각 매장의 총 시스템 수를 구할 수있는 방법이 있습니까?

SELECT 
    s.Id as Store, 
    COUNT(Distinct SystemsIden) as NumOfSystems, 
    COUNT(distinct ProductIden) as NumOfProduct, 
    CAST(COUNT(distinct ProductIden)as float)/CAST(COUNT(Distinct SystemsIden) as 
    float) as average 
FROM 
Store s 
    INNER JOIN 
    (
    Select systemsiden,CustomerIden,ProductIden, Customer.StoreId as 
    storeiden from 
(
    select Product.ID as ProductIden, System.Id as systemsiden, System.customerId as CustomerIden from product join Ssystem On System.Id = Product.SystemIdId 
) 
    table1 join Customer 
    on Customer.Id = CustomerIden 
) 
    table2 On s.Id = storeiden 
GROUP BY 
    s.Id 
+0

? 십진법을 사용해야합니다. 수레는 대략적인 데이터 유형입니다. –

+0

@Dan 기회는 mysql 또는 sql-server 중 하나를 사용하고있는 것입니다. 코드가 실제로 두 데이터베이스 모두에서 실행되어야하는 경우가 아니면 실제 용도로 사용되지 않으므로 다른 태그를 질문에서 제거하십시오. –

답변

1

광범위한 하위 쿼리 사용에 대한 필요가 없습니다, 간단한 외부 충분합니다 조인 : 왜 당신이 당신의 수를 수레하기를 캐스팅

SELECT st.Id, 
     COUNT(DISTINCT sy.Id) AS SystemCount, 
     COUNT(DISTINCT pr.Id) AS ProductCount, 
     CASE WHEN COUNT(DISTINCT sy.Id) = 0 THEN 0 
      ELSE 1.0 * COUNT(DISTINCT pr.Id)/COUNT(DISTINCT sy.Id) 
     END AS Average 
FROM Store AS st 
LEFT JOIN Customer AS cu ON cu.DealerId = st.Id 
LEFT JOIN System AS sy ON sy.CustomerId = cu.Id 
LEFT JOIN Product AS pr ON pr.SystemId = sy.Id 
GROUP BY st.Id; 

query results

+0

오류 메시지 : 메시지 8134, 수준 16, 상태 1, 줄 36 0으로 나누기 오류가 발생했습니다. 경고 : Null 값은 집계 또는 다른 SET 작업에 의해 제거됩니다. – Dan

+0

예제 데이터가 주어집니다. ISNULL을 사용하도록 업데이트되었습니다. –

+0

나는 여전히 그 오류가 발생했습니다. – Dan

0
SELECT 
    s.Id as Store, 
    COUNT(DISTINCT sys.id) as NumOfSystems, 
    COUNT(DISTINCT p.id) as NumOfProduct, 
    IFNULL(COUNT(DISTINCT p.id),0)/IFNULL(COUNT(Distinct sys.id),1) as average 
FROM Store s 
INNER JOIN Customer c 
ON c.dealerId = s.id 
INNER JOIN System sys 
ON sys.customerId = c.id 
INNER JOIN product p 
ON sys.id=p.systemId 
GROUP BY s.Id 
관련 문제