将特定的sql查询结果组合为一个字符串



我有以下查询;

SELECT custom.name, instance_id 
FROM table1 tb 
WHERE tb.instance_id = 1111 OR tb.instance_id = 2222

这将返回以下结果;

test, 1111
test1, 1111
test3, 1111
tabletest, 2222
tabletest1, 2222
tabletest2, 2222

我希望能够匹配instances_id,并将匹配的行组合成一个字符串。

test;test1;test3
tabletest;tabletest1;tabletest2

我可以得到一个字符串,但目前这会获取所有结果并将其放入一个字符串中。

STUFF((
SELECT custom.name + ';'
FROM table1 tb 
WHERE tb.instance_id = 1111 OR tb.instance_id = 222
FOR XML PATH(' '), TYPE.value('.', 'NVARCHAR(MAX)'), 1, 0, ' ')

这导致

test;test1;test3;tabletest;tabletest1;tabletest2

不幸的是,我无法升级过去的sql server版本15,这可能会限制我。

子查询中需要一个相关子句。我建议:

SELECT v.instance_id,
STUFF((SELECT ';' + tb.name 
FROM table1 tb 
WHERE tb.instance_id = v.instance_id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'
), 1, 1, ' '
)
FROM (VALUES (1111), (2222)) v(instance_id);

这里有一个db<gt;不停摆弄

数据

drop table if exists dbo.tTable;
go
create table dbo.tTable(
[name]                varchar(100) not null,
instance_id           int not null);
insert dbo.tTable values
('test',1111),
('test1',1111),
('test3',1111),
('test',2222),
('test1',2222),
('test2',2222);

查询

select instance_id, 
stuff((select ';' + cast([name] as varchar(100))
from tTable c2
where t.instance_id = c2.instance_id
order by [name] FOR XML PATH('')), 1, 1, '') [value1]
from tTable t
group by instance_id;

输出

instance_id value1
1111        test;test1;test3
2222        test;test1;test2

最新更新