1
0

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 1 year has passed since last update.

SQLServerで複数行のデータをカンマ区切りで1行にする

Last updated at Posted at 2023-05-11

やりたいこと

group byで同じデータを集約するとき、複数行を1行の文字列としてまとめたい。
GROUP_CONCAT や ARRAY_TO_STRING のようなことをSQLServreで実装したい。

方法

STRING_AGG 集計関数を使うとできそう。

STRING_AGG (Transact-SQL) - SQL Server | Microsoft Learn
https://learn.microsoft.com/ja-jp/sql/t-sql/functions/string-agg-transact-sql

やってみる

TBL
Bunrui Col1
------ ----------
精肉     1:豚肉
精肉     2:牛肉
精肉     3:鶏肉
精肉     4:合挽
青果     1:トマト
青果     2:りんご
青果     3:きゅうり
STRING_AGG 集計関数 のサンプル
SELECT
	 TBL.Bunrui
	,STRING_AGG( CONVERT(VARCHAR(max), TBL.Col1), ',') AS Result
FROM
	(
			SELECT '精肉' AS Bunrui, '1:豚肉' AS Col1
	UNION	SELECT '精肉' AS Bunrui, '2:牛肉' AS Col1
	UNION	SELECT '精肉' AS Bunrui, '3:鶏肉' AS Col1
	UNION	SELECT '精肉' AS Bunrui, '4:合挽' AS Col1
	UNION	SELECT '青果' AS Bunrui, '1:トマト' AS Col1
	UNION	SELECT '青果' AS Bunrui, '2:りんご' AS Col1
	UNION	SELECT '青果' AS Bunrui, '3:きゅうり' AS Col1
	) AS TBL
GROUP BY
	TBL.Bunrui
;

Bunrui Result
------ ------------------------------
精肉     1:豚肉,2:牛肉,3:鶏肉,4:合挽        
青果     1:トマト,2:りんご,3:きゅうり               

集計関数内の並び替え

STRING_AGG の後ろに WITHIN GROUP を追加。

STRING_AGG 集計関数 のサンプル (降順指定)
SELECT
	 TBL.Bunrui
	,STRING_AGG( CONVERT(VARCHAR(max), TBL.Col1), ',') WITHIN GROUP (ORDER BY TBL.Col1 DESC) AS Result
FROM
	(
			SELECT '精肉' AS Bunrui, '1:豚肉' AS Col1
	UNION	SELECT '精肉' AS Bunrui, '2:牛肉' AS Col1
	UNION	SELECT '精肉' AS Bunrui, '3:鶏肉' AS Col1
	UNION	SELECT '精肉' AS Bunrui, '4:合挽' AS Col1
	UNION	SELECT '青果' AS Bunrui, '1:トマト' AS Col1
	UNION	SELECT '青果' AS Bunrui, '2:りんご' AS Col1
	UNION	SELECT '青果' AS Bunrui, '3:きゅうり' AS Col1
	) AS TBL
GROUP BY
	TBL.Bunrui
;

Bunrui Result
------ ------------------------------
精肉     4:合挽,3:鶏肉,2:牛肉,1:豚肉        
青果     3:きゅうり,2:りんご,1:トマト    
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?