在SQL SERVER中具有等效连接的Group_Concat

时间:2016-04-28 06:45:27

标签: sql-server string-aggregation

我的代码遇到了问题。我曾经在MySQL上,但我已将我的代码迁移到SQL Server。

现在我遇到了这个GROUP_CONCAT函数的问题。我找到了一些潜力'相当于但它不会导致预期的结果。

以下是查询:

SELECT 
  GROUP_CONCAT(c.namecheck SEPARATOR '; ') AS GROUPNAME
FROM db_name a
left JOIN db_employee b ON a.nameId = b.empID
left join db_civ c ON b.nameNum = c.civNum

我尝试了一些。但正如我所说,它并没有输出我期望的结果(因为我在MySQL中反击查询)

预期输出应为

-----------
|GROUPNAME|
-----------
|Jay; Ron; Jorge .... etc|
|                        |
|                        |
|                        |

1 个答案:

答案 0 :(得分:3)

在SQL Server中,使用FOR XML PATH将行值连接成字符串。

CREATE TABLE states (id int, statename nvarchar(20))
INSERT states SELECT 1, 'Texas'
INSERT states SELECT 2, 'Florida'
INSERT states SELECT 3, 'California'

CREATE TABLE capitals (id int, cityname nvarchar(20))
INSERT capitals SELECT 1, 'Austin'
INSERT capitals SELECT 2, 'Tallahassee'
INSERT capitals SELECT 2, 'Sacramento'

--The wrapper removes the leading delimiter
SELECT STUFF((
    SELECT  DISTINCT '; ' + c.cityname  --Specify delimiter
    FROM    states s
    JOIN    capitals c ON c.id = s.id
    FOR XML PATH ('')                   --This does the concatenation
), 1, 1, '' )

输出是:

Austin; Sacramento; Tallahassee

对于您的示例,它将是:

--The wrapper removes the leading delimiter
SELECT STUFF((
    SELECT  DISTINCT '; ' + c.namecheck  --Specify delimiter
    FROM db_name a
    left JOIN db_employee b ON a.nameId = b.empID
    left join db_civ c ON b.nameNum = c.civNum
    FOR XML PATH ('')                   --This does the concatenation
), 1, 1, '' ) AS GROUPNAME