在SQL Server中创建逗号分隔的结果

时间:2011-11-09 17:34:10

标签: sql sql-server-2008 tsql

  

可能重复:
  Simulating group_concat MySQL function in MS SQL Server 2005?
  Concat field value to string in SQL Server

涉及2个表,用户和关键字。

用户
用户id
的firstName
lastName的
...

关键字
用户id
关键字

如果我运行此查询:

select u.userId, u.firstName, u.lastName, k.keyword 
from Users as u 
inner join  Keywords as k on u.userId = k.userId

我得到这样的东西:

enter image description here

我想要的是:

enter image description here

This looked very similar to what I wanted但我似乎无法让它正常工作。

3 个答案:

答案 0 :(得分:1)

SELECT
       u.userId,
       u.firstName,
       u.lastName,
       (select keyword +', ' from Keywords tk where tk.userid= u.userid for xml path ('')  )   as keyword
  FROM
       Users AS u 

要测试的示例查询:

declare @Users as table(
userid int,
firstname varchar(20),
lastname varchar(20)

)

declare @Keywords as table(
userid int,
keyword varchar(20)

)

insert into @Users
values(
1, 'Bob','Sanders'
),
(
2, 'Jamie','Smith'
)

insert into @Keywords
values 
(1,'Cars'),
(1,'Pizza'),
(2,'Tomato'),
(2,'Blah')

SELECT
       u.userId,
       u.firstName,
       u.lastName,
       (select keyword +', ' from @Keywords tk where tk.userid= u.userid for xml path ('')  )   as keyword
  FROM
       @Users AS u 

返回:

userId  firstName   lastName    keyword
1       Bob         Sanders     Cars, Pizza, 
2       Jamie       Smith       Tomato, Blah, 

答案 1 :(得分:1)

;WITH a AS (
  SELECT 
    u.userId,
    u.firstName,
    u.lastName,
    ( SELECT k.keyword + ',' 
      FROM Keywords k
      WHERE k.userId = u.userId
      ORDER BY k.keyword
      FOR XML PATH('') 
    ) AS [keyword]
  FROM Users u
)
SELECT 
  a.userId,
  a.firstName,
  a.lastName,
  -- strip off trailing comma
  LEFT(
    a.keyword, 
    LEN(a.keyword)-1
  ) AS keyword
FROM a   

答案 2 :(得分:0)

您可以创建一个新的sql聚合函数concat来连接文本并在查询中使用if:

select userId, firstName, Lastname, concat(Keyword)
from Users
group by userId, firstName, Lastname;

Follwoing链接显示了如何创建concat功能的示例。 http://msdn.microsoft.com/en-us/library/ms182741.aspx