SQL:如何将结果与单个用户连接起来?

时间:2014-03-30 15:37:11

标签: sql

username      Name                    Skills
zainniazi     Zain Khan NiaZi         C
zainniazi     Zain Khan NiaZi         C++

如何在技能连接的单行中获得结果?像:

username      Name                    Skills
zainniazi     Zain Khan NiaZi         C,C++

1 个答案:

答案 0 :(得分:2)

试试这个:

SQL SERVER

SELECT
      T1.username
    , T1.Name
    , Skills = STUFF((
          SELECT ',' + T2.Skills
          FROM TableName T2
          WHERE T1.username = T2.username
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM TableName T1
GROUP BY T1.username,T1.Name
ORDER BY T1.username

请参阅SQL Fiddle中的SQL SERVER示例。

<强> MYSQL

SELECT username,Name,GROUP_CONCAT(Skills) 
FROM TableName
GROUP BY username,Name

请参阅SQL Fiddle中的MySQL示例。

<强>结果:

USERNAME    NAME              SKILLS
zainniazi   Zain Khan NiaZi   C,C++