T-SQL将行连接成字符串

时间:2021-07-09 14:16:46

I'm trying to use a sub query on a select statement for a field value but I can't seem to figure out the correct syntax. I want to pull a list of company names and as a field for that query, I want to select all the employees for that company.

我正在尝试在select语句中使用子查询来获取字段值,但我似乎无法弄清楚正确的语法。我想提取公司名称列表,并作为该查询的字段,我想选择该公司的所有员工。

Any ideas on what I'm doing wrong? The error I get is

关于我做错的任何想法?我得到的错误是

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

当未使用EXISTS引入子查询时,只能在选择列表中指定一个表达式

T-SQL code:

T-SQL代码:

SELECT 
   company_name, 
   company_type, 
   (SELECT 
        employee_firstname, employee_lastname 
    FROM 
        tblemployees 
    WHERE 
        tblemployees.company_id = tblCompanies.company_id) as employees 
FROM 
    tblCompanies

Desired output:

期望的输出:

Company Name |  Company Type  | Employees
----------------------------------------------------------
Test Co      |  Construction  | Bob Smith, Jack Smith, etc

1 个解决方案

#1


9  

You'll need to concatenate the first and last names using FOR XML PATH or a similar solution. More details on the various methods here.

您需要使用FOR XML PATH或类似的解决方案来连接名字和姓氏。这里有关于各种方法的更多细节。

SELECT DISTINCT
   c1.company_name, 
   c1.company_type,
   STUFF((SELECT
              ', ' + c2.employee_firstname + ' ' + c2.employee_lastname
          FROM
              tblCompanies c2
          WHERE
              c1.company_id = c2.company_id
          ORDER BY
              employee_lastname, employee_firstname
          FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 1, '')
FROM tblCompanies c1

SQL Fiddle

SQL小提琴

#1


9  

You'll need to concatenate the first and last names using FOR XML PATH or a similar solution. More details on the various methods here.

您需要使用FOR XML PATH或类似的解决方案来连接名字和姓氏。这里有关于各种方法的更多细节。

SELECT DISTINCT
   c1.company_name, 
   c1.company_type,
   STUFF((SELECT
              ', ' + c2.employee_firstname + ' ' + c2.employee_lastname
          FROM
              tblCompanies c2
          WHERE
              c1.company_id = c2.company_id
          ORDER BY
              employee_lastname, employee_firstname
          FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 1, '')
FROM tblCompanies c1

SQL Fiddle

SQL小提琴