gpt4 book ai didi

sql-server - T-SQL 将行连接成字符串

转载 作者:行者123 更新时间:2023-12-02 16:05:08 25 4
gpt4 key购买 nike

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

关于我做错了什么有什么想法吗?我得到的错误是

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

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

期望的输出:

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

最佳答案

您需要使用 FOR XML PATH 或类似的解决方案连接名字和姓氏。有关各种方法的更多详细信息here .

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-server - T-SQL 将行连接成字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com