본문 바로가기

Algorithm

[SQL 알고리즘] SolvedSql - 지역별 주문의 특징

✅ 문제

https://solvesql.com/problems/characteristics-of-orders/

 

https://solvesql.com/problems/characteristics-of-orders/

 

solvesql.com

 

✅ 코드

select region as Region,
(select count(DISTINCT order_id) from records s where s.region = r.region and category = "Furniture") as Furniture,
(select count(DISTINCT order_id) from records s where s.region = r.region and category = "Office Supplies") as "Office Supplies",
(select count(DISTINCT order_id) from records s where s.region = r.region and category = "Technology") as Technology
from records r group by region;

 

 

처음에 생각난건 피벗함수였는데 잘 모르고 어떻게 쓰는지를 안써봐서 생가나는대로 위에 코드로 작성해서 정답은 맞췄다.

그렇지마 피벗함수로는 어떻게 풀지하고 공부하게되었다.

 

✏️PIVOT 함수?

 

행의 데이터를 열로 변환하여 요약 정보를 표시하는 방법이다.

  • 주로 데이터를 요약하거나 집계하기 위해 사용
  • 특정 열의 고유 값들을 새로운 열로 변환하고, 다른 열의 값을 이 열에 대응하여 집계

🔎사용방법

SELECT [fixed_column], [new_column_based_row_values]
FROM (
    SELECT [original_columns]
    FROM [original_table]
) AS SourceTable
PIVOT (
    [Aggregation Function](column_to_aggregate)
    FOR [column_to_transform] IN ([new_column_1], [new_column_2], [new_column_3])
) AS PivotTable;

 

  • fixed_column: 피봇테이블으로 변환 후에도 유지되는 열 (그룹화 기준 1)
  • new_column_based_row_values: 레코드 값을 통해 새로운 컬럼을 형성할 컬럼
  • original_columns/original_table: 원본 컬럼과 테이블
  • Aggregation Function/column_to_aggregate: 집계 함수와 집계할 컬럼
  • column_to_transform: 피봇테이블의 새로운 열로 만들 컬럼 (그룹화의 기준 2)
  • new_column: column_to_transform 컬럼의 값들
  • AS SourceTable/AS PivotTable: 일부 RDBMS(SQL Server, Oracle 등)에서는 서브쿼리와 PIVOT에 엘리어스가 필수적이므로 붙이는 편이 좋다.

 

위와같은 방법으로 코드를 작성하면 다음과같지만 SQL Lite에서는 피벗테이블을 지원하지않아서 결과는 확인하지 못했다.

 

SELECT region "Region", "Furniture", "Office Supplies", "Technology"
FROM (
  SELECT region, category, order_id
  FROM records
) AS base_table
PIVOT (
  count(order_id)
  FOR category IN ("Furniture", "Office Supplies", "Technology")
) AS pivot_table
ORDER BY 1;

 

또한 위의 코드에서 컬럼명을 표시할 때 더블쿼트" "를 사용했는데, 이는 Oracle에서는 정상작동하지만 SQL Server의 경우 대괄호[ ]를 사용해야한다고 한다.
더블쿼트를 사용하는 것이 SQL 표준이나, 종종 백틱` `을 사용해야 하는 경우도 있다고 하니 어떤 RDBMS를 사용하는지 확인하고 이에 맞는 문법을 체크하는 것이 좋겠다.