3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLのGroupで、文字列を集計

Last updated at Posted at 2018-08-21

SQLで、集計がよく行うことなんですが、普通は合計値(SUM)、最大最小(MAX,MIN)など、やっていると思います。
文字列のカラムに対して、一行にまとめ出したいケース:
例えばこういうデータがあり:

userid skill
1001 R
1001 java
1001 python
1001 shell
1002 work
1002 excel

GROUP BY でユーザー単位でスキルを出す

userid skill
1001 R,java,python,shell
1002 work,excel

SQLServerなら、SQLはこうなります:

SELECT 
userid
,skill = stuff(
  (SELECT  ',' + skill
  FROM table AS t
  WHERE t1.userid = t2.userid FOR xml path('')), 1, 1, '')
FROM table t2
GROUP BY userid

postgresなら、関数があるので、便利です。


select 
userid
,array_to_string(ag,',')
from (
	select 
	userid
	,array_agg(skill) ag  
	from table 
	group by userid
)a

まだ、string_agg()関数もう利用できます。

ちなみに、REDSHIFTは関数名がちょっと異なります


select
  userid
 ,listagg(skill,',')
within group (order by skill)
from table
group by 1
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?