찌니의 프로그래밍 삼매경

[SQL] postgreSQL ARRAY 배열함수 unnest, array_agg, array_to_string 본문

SQL/SQL공부

[SQL] postgreSQL ARRAY 배열함수 unnest, array_agg, array_to_string

zzI니☆ 2022. 3. 26. 00:53
728x90

row 를 array 또는 string으로 변환하기

1. unnest() 는 array 데이터를 row로 변환

unnest 결과는 하단의 내용과 같다


2. array_agg, array_agg_string 적용

결과는 하단의 내용과 같다

array_agg 는 group by와 함께 사용하는 함수이다. group by 된 값들을 array로 반환.

distinct  order by 를 함께 이용하면 중복제거된 값을 구하거나, 원하는 순서로 정렬하여 array를 만들 수 있다.

ex : array_agg(distinct col2 order by col2)


 

-- 임시테이블 생성하여 테스트진행

with make_array as (
	select unnest(array['고기', '고기', '고기', '채소', '채소']) as col1
	     , unnest(array['삼겹살', '항정살', '가브리살', '상추', '명이나물']) as col2
)
select
    x.col1
    , array_agg(x.col2) as array_agg결과
    , array_to_string(array_agg(x.col2),',') as array_to_string결과
from make_array x
group by x.col1;

-- 🌟 distinct , order by 사용가능
select
    x.col1
    , array_agg(distinct x.col2 order by x.col2) as array_agg결과
    , array_to_string(array_agg(distinct x.col2 order by x.col2),',') as array_to_string결과
from make_array x
group by x.col1;
728x90
Comments