首页 > 解决方案 > 将特定的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,并将匹配的行组合成一个字符串。

IE

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,这可能会限制我。

标签: sqlsql-server

解决方案


数据

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

推荐阅读