4
2

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 5 years have passed since last update.

T-SQLでテーブルの文字列項目をカンマ区切りで結合したい場合

Last updated at Posted at 2016-06-29

あるテーブルのある項目をカンマ区切りで結合したい場合は、 XML PATHを使う事でSQLで取得することができる。

単一項目を結合する場合

Select 
  Left(Main.UserNames,Len(Main.UserNames)-1) As "UserNames"
From
  (
    SELECT 
      (
        Select 
          UserName + ',' AS [text()]
        From 
          dbo.UserMaster 
        For XML PATH ('')
      ) AS UserNames
  ) [Main]

グループ化して結合する場合

※こっちは参考のリンク先のSQLをほぼそのままお借りしてます

Select 
  Main.UserId,
  Left(Main.Users,Len(Main.Users)-1) As "Users"
From
  (
    Select 
      distinct U2.UserId, 
      (
        Select 
          U1.UserName + ',' AS [text()]
        From 
          dbo.Users U1
        Where 
          U1.UserId = U2.UserId
        ORDER BY U1.UserId
        For XML PATH ('')
       ) [Users]
    From dbo.Users U2
  ) [Main]

参考

Concatenate many rows into a single text string?

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?