따`ddah 2025. 1. 14. 18:11

group by 에러 모음 zip...

Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'ecommerce.od.order_detail_id' which is not functionally dependent on columns in GROUP BY clause
Error Code: 1052. Column 'product_id' in group statement is ambiguous

확실히 기초부터 공부하지 않으니까 공부할 때 막히는 부분이 많았다.
 
기초 공부를 확실히 하자...라는 다짐을 하게 되었다...


제품 별 매출 파악하기

 
매출 = 가격 * 수량 [ 칼럼명(테이블명) ]
revenue = price(products) * quantity(order_details)
 
이때 두 개의 테이블을 join 해야 하기 때문에 product_id로 join을 했다.

select *
from order_details od
join products p on od.product_id = p.product_id;

 
해당 표에서 product_id 값이 중복으로 들어가기 때문에 product_id를 기준으로 group by를 해서 정리하려고 했다.
 
근데... 에러가 뜨네..?
 
그래서 찾아본 group by 규칙


GROUP BY 규칙

  • group by에 명시된 칼럼(열)만 select 할 수 있다.
  • group by에 명시되지 않은 칼럼을 select 하려면 집계 함수를 사용해야 한다. 
  • 집계 함수 : SUM, AVG, MAX, MIN
select
    od.product_id,                      -- GROUP BY에 포함된 열 (OK)
    (od.quantity * p.price) as revenue  -- GROUP BY에 포함되지 않은 열 (문제 발생)
from 
    order_details od
join 
    products p on od.product_id = p.product_id
group by 
    od.product_id;

 

최종 코드

select
    od.product_id,                         -- GROUP BY에 포함된 열 (OK)
    sum(od.quantity * p.price) as revenue  -- GROUP BY에 포함되지 않은 열이지만 집계함수 사용 (OK)
from 
    order_details od
join 
    products p on od.product_id = p.product_id
group by 
    od.product_id;

 
하지만 만약 group by 없이 하려면 이렇게 쿼리를 짤 수도 있다.

select
    od.product_id,
    (od.quantity * p.price) as revenue -- 각 주문 항목별 수익 계산
from 
    order_details od
join 
    products p on od.product_id = p.product_id;
728x90