XML 路径 SQL 服务器

XML PATH SQL SERVER

我有资料

TIPE| NILAI
PSX     10
GE      10
EG      10
SX      20
SXL     20
SZ      20

如何获得类似

的输出
psx/ge/eg = 10
sx/sxl/sz = 20

这是我的语法

ISNULL(CAST((SELECT CONVERT(VARCHAR,TIPE) + ' / '        
FROM tabel
FOR XML PATH('')) AS varchar(max)),'')

试试这个:

declare @tbl table (TIPE varchar(5), NILAI int);
insert into @tbl values
('PSX', 10),
('GE', 10),
('EG', 10),
('SX', 20),
('SXL', 20),
('SZ', 20);

select NILAI,
       (select TIPE + '/' from @tbl where t.NILAI = NILAI for xml path('')) [TIPE]
from @tbl t
group by NILAI

--for sql server 2017 or newer
select NILAI, string_agg(TIPE, '/') TIPE
from @tbl
group by NILAI

试试这个

DECLARE @tbl table (TIPE varchar(5), NILAI int);
insert into @tbl values
('PSX', 10),
('GE', 10),
('EG', 10),
('SX', 20),
('SXL', 20),
('SZ', 20);
SELECT DISTINCT  STUFF((SELECT '/ '+TIPE 
        FROM @tbl i WHERE i.NILAI=o.NILAI FOR XML PATH ('')),1,1,'')
              + ' = ' + CAST(NILAI AS VARCHAR) AS [RequiredResult] 
FROM @tbl o

结果

RequiredResult
--------------------
 PSX/ GE/ EG = 10
 SX/ SXL/ SZ = 20

演示:http://rextester.com/WYAJ22189