sql - 将特定的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,这可能会限制我。
解决方案
数据
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
推荐阅读
- c++ - gcovr 总是显示 100% 的线路覆盖率
- python-3.x - 一个函数中的用户定义输入在另一个函数Python中不返回值
- mysql - 如何仅使用最后一个事务来计算 timediff mysql 5.7
- python - 如何在 Python 中使用零偏度对数变换
- python - 将 Tensorflow1.12 模型转换为 Tensorflow Lite (TFLite)
- c - 为什么使用 libc 会阻止货物正确链接我的程序?
- spring - 通过 CompletableFuture 工作的 Spring-boot 异步控制器同步
- html - 用 html5 SVG 设计日食圆
- php - 不同路线的相同网址 laravel
- python - python中的最小二乘GELS LAPACK例程 - 它存在吗?