sql-server - 将 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
这可能吗?我认为是,但是按三列分组让我很生气。
解决方案
基于@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, '')
.
推荐阅读
- api - 在 .net core API 的 httpresponse 内容中发送 json 数据
- javascript - @ViewChildren 中的 QueryList 的顺序是否总是与 DOM 中的顺序相匹配?
- c# - 实体类型上已存在同名的属性或导航 - 如何在实体框架的迁移场景中添加外键
- r - 如何根据上一行的月份连续增加一个月?
- mongoose - Mongoose 动态查询结构“全部”或某些元素
- rust - 如何将负 i32 数添加到 usize 变量?
- asp.net-core - ASP.NET Core 启动类不遵循打开/关闭原则
- cassandra - Cassandra 行缓存只能缓存在特定列上吗?
- php - 无法将字符串(字母)插入 mysql 。数字工作正常
- reactjs - 将图像添加到 DevExtreme React Grid Bootstrap4 列