기본 콘텐츠로 건너뛰기

[MySQL] GROUP_CONCAT 사용하기

필요에 의해 서로 다른 결과를 한줄로 합쳐서 보여줘야 할 경우가 있다.

전체 결과값을 가져와서 java 와 같은 프로그램 언어에서 for 문을 돌며 문자열을 붙여도 되긴 하지만
Select 쿼리를 던질때 결과값으로 합쳐져 있는 문자열을 받는게 더 편하다.



select * from test ;

type

name

 fruit

수박

 fruit

사과
 fruit

바나나

 fruit
사과



select type, group_concat(name) from test group by type ;

type

name

 fruit

수박,사과,바나나,사과





group_concat을 기본적인 형태로 사용했을경우 문자열 사이에 쉼표(,)가 붙게 된다.
구분자를 변경하고 싶을때는 아래와 같이 SEPARATOR '구분자' 를 붙여 준다.

select type, group_concat(name separator '|') from test group by type ;

type

name

 fruit

수박|사과|바나나|사과



합쳐지는 문자열에 중복되는 문자열을 제거 할때는 distinct 를 사용한다.

select type, group_concat(distinct name) from test group by type ;

type

name

 fruit

수박,사과,바나나





엄청 고민했는데 찾았다..ㅋㅋㅋㅋㅋ 구글링....


문자열을 정렬하여 나타내고 싶으면 order by 를 이용한다.

select type, group_concat(distinct name order by name) from test group by type ;

type

name

 fruit

바나나,사과,수박



[정리]
MySQL에서 group by 로 문자열을 합칠땐 group_concat 을 이용한다.

1. 기본형 : group_concat(필드명)
2. 구분자 변경 : group_concat(필드명 separator '구분자')
3. 중복제거 : group_concat(distinct 필드명)
4. 문자열 정렬 : group_concat(필드명 order by 필드명)



[참고]
MySQL Group BY function

Name Description
AVG() Return the average value of the argument
BIT_AND() Return bitwise and
BIT_OR() Return bitwise or
BIT_XOR() Return bitwise xor
COUNT(DISTINCT) Return the count of a number of different values
COUNT() Return a count of the number of rows returned
GROUP_CONCAT() Return a concatenated string
MAX() Return the maximum value
MIN() Return the minimum value
STD() Return the population standard deviation
STDDEV_POP() Return the population standard deviation
STDDEV_SAMP() Return the sample standard deviation
STDDEV() Return the population standard deviation
SUM() Return the sum
VAR_POP() Return the population standard variance
VAR_SAMP() Return the sample variance
VARIANCE() Return the population standard variance
URL : http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html



[TIP]
오라클의 경우 mysql의 group_concat을 아래와 같이 대체하여 사용이 가능하다.
오라클 10G : WM_CONCAT()
오라클 11G : LISTAGG()

댓글

이 블로그의 인기 게시물

UltraEdit Professional Version 18.20.0.1014 라이센스 키 넣기

Step 1: unpack rar archive      Step 2: run the setup   Step 3: Use the given keygen to activate    Add the line   127.0.0.1 licensing.ultraedit.com         to your %WINDOWS%\system32\drivers\etc\hosts file                 Enter any data for license-id and password (license-id must be a         number)                 Choose Offline activation and generate corresponding activation         codes for your user codes   Step 4: Enjoy and Support Developers, Buy It, They Deserved It!

gsjava WeGuardia™ SSLplus 특징(퓨쳐시스템 => 퓨쳐텍정보통신으로 이관)

☎ 문의 :  010-3240-0041 김성은 소장 01.   웹기반   인터페이스   제공 ……. –  웹기반   인터관리   및   사용   편리성을   제공 ……. –  실시간 터널수, 실시간 위반 사용자 등   복잡   정교한   정보   표시를   구현 02.   사용자를   위한   다양한   클라이언트   제공 ……. –  윈도우 , IOS,MAC, 안드로이드   및   리눅스   클라이언트   제공 ……. –  항시   암호화된   네트워크   연결성 ,  보안성   및   단말  Compliance  등  NAC  기능 03.   사용자   친화적   앱   목록 ……. – OS 별 앱 목록을 등록후 사용 가능 ……. –  사용자는   접속   정보   기억   불필요 ,  접속   후 ,  앱   목록에서   원하는   앱을   선택하여   클릭 ……. –  기업   필수   앱   배포   가능 04.   효율적인  VPN Tunneling ……. – Non Split Tunneling 과  Split Tunneling 을   지원 ,  업무   트래픽과   일반   인터넷   트래픽   분리   처리   가능 ……. – WeGuardia™SSLplus  보안설정을 ...