繁体   English   中英

将特定的sql查询结果合并成一个字符串

[英]Combining specific sql query results into one string

我有以下查询;

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

我希望能够匹配instance_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,这可能会限制我。

您需要在子查询中使用相关子句。 我会建议:

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<>fiddle。

数据

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM