올바르게 가입하고 그룹화 할 수 있습니다
-
20-12-2019 - |
문제
이하
아래에있는 기본 구조가 있습니다.Sales.Customers Sales.Orders Sales.OrderDetails
--------------- ------------ ------------------
country orderid orderid
custid custid qty
.
이므로 미국 고객을 반환해야하며, 각 고객은 총 주문 수와 총 수량을 반환합니다.나는 그런 쿼리를 썼습니다 :
SELECT
C.custid, SUM(O.orderid) as numorders,
SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
JOIN Sales.Orders AS O
ON C.custid = O.custid
JOIN Sales.OrderDetails AS OD
ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid;
.
불행히도 나는 그런 결과를 얻는다 :
custid numorders totalqty
----------- ----------- -----------
32 235946 345
36 94228 122
43 21027 20
....... ..... ....
.
대신
custid numorders totalqty
----------- ----------- -----------
32 11 345
36 5 122
.
실수가있는 곳을 이해할 수 없습니다.
해결책
이렇게해야합니다 :
SELECT C.custid,
COUNT(DISTINCT O.orderid) as numorders,
SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
INNER JOIN Sales.Orders AS O
ON C.custid = O.custid
INNER JOIN Sales.OrderDetails AS OD
ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid
ORDER BY C.custid;
. 다른 팁
조금 더 읽을 때 두 가지가 잘못되었습니다.계산 대신 주문을 합산하고 수량을 그룹화하고 있습니다. 시도해보십시오 :
SELECT
C.custid,
COUNT(distinct O.orderid) as numorders,
SUM(OD.qty) as totalqty
FROM Sales.Customers AS C
JOIN Sales.Orders AS O
ON C.custid = O.custid
JOIN Sales.OrderDetails AS OD
ON O.orderid = OD.orderid
WHERE country = 'USA'
GROUP BY C.custid
ORDER BY C.custid;
. 제휴하지 않습니다 StackOverflow