首页 > 解决方案 > 将 SELECT 连接到 SQL Server 中的一列

问题描述

我确实仔细研究了关于此发布的所有各种内容,但我无法让它们中的任何一个工作,可能是因为我使用的表没有任何标识列(愚蠢,愚蠢,愚蠢!)。

我在名为 的列中列出了与租约相关联的所有联系人的列表file_as_name。该表被称为lease_contacts不足为奇。

在另一个表中,我有一个大字符列,当表按“名称、单位、租约开始日期”分组时,我需要将连接的结果填充到该列中。

换句话说,对于名为“Cedar Villas”和“Unit 001”且 Lease_start_date = “01/01/2019”的物业的一组人,我有以下值:

John Doe
Jane Smith
Allen Smithee

在专栏中,我想放置:

John Doe, Jane Smith, Allen Smithee

这可能吗?我认为是,但是按三列分组让我很生气。

标签: sql-serversql-server-2008

解决方案


基于@shawnt00 在重复问题中提到的 Transact-SQL 链接中的连接行值,您可以使用 STUFF/XML 方法执行此操作,例如:

declare @lease_contacts table (
    [name] nvarchar(50),
    unit nvarchar(50),
    lease_start_date date,
    file_as_name nvarchar(50)
);

insert @lease_contacts values
    (N'Cedar Villas', N'Unit 001', '2019-01-01', N'John Doe'),
    (N'Cedar Villas', N'Unit 001', '2019-01-01', N'Jane Smith'),
    (N'Cedar Villas', N'Unit 001', '2019-01-01', N'Allen Smithee');

select  stuff((
    select  N', ' + file_as_name
    from    @lease_contacts
    where   [name] = N'Cedar Villas'
    and unit = N'Unit 001'
    and lease_start_date = '2019-01-01'
    for xml path(''), type).value('.', 'nvarchar(max)')
    , 1, 2, N'')

这给了你:

(No column name)
------------------------------------
John Doe, Jane Smith, Allen Smithee

注意:大多数引用STUFF(..., 1, 1, '')在处理普通逗号分隔符时使用,即:','. 因为您想使用', '空间,所以需要将其调整为STUFF(..., 1, 2, '').


推荐阅读