작성
·
276
1
서브쿼리 예제 답으로
CustomerID 별 ShipperID_1,2,3 개수를 구하였는데
칼럼을 추가하여 ShipperID_Sum 값을 구하려면 어떻게 해야할까요? (ShipperID_1,2,3의 총합)
ex) CutomerID '5'의 경우
ShipperID_1 = 1
ShipperID_2 = 1
ShipperID_3 = 1 인데,
ShipperID_Sum = 3이 보이게끔 칼럼을 추가하고 싶습니다.
답변 1
0
스스로 정답을 찾아서 내용 공유합니다!
WITH(임시 테이블)라는 것을 사용하여 해결할 수 있었네요.
With Temp_table as
(
SELECT C.CustomerID,
IFNULL(O1.ShipperID_1, 0) AS S1,
IFNULL(O2.ShipperID_2, 0) AS S2,
IFNULL(O3.ShipperID_3, 0) AS S3
FROM Customers AS C
LEFT JOIN (
SELECT CustomerID, Count(OrderID) AS ShipperID_1
FROM Orders
WHERE ShipperID = 1
Group By CustomerID
) AS O1
ON O1.CustomerID = C.CustomerID
LEFT JOIN (
SELECT CustomerID, Count(OrderID) AS ShipperID_2
FROM Orders
WHERE ShipperID = 2
Group By CustomerID
) AS O2
ON O2.CustomerID = C.CustomerID
LEFT JOIN (
SELECT CustomerID, Count(OrderID) AS ShipperID_3
FROM Orders
WHERE ShipperID = 3
Group By CustomerID
) AS O3
ON O3.CustomerID = C.CustomerID
)
Select CustomerID, S1, S2, S3, S1+S2+S3 AS SUM
From Temp_table