XML PATH SQL SERVER

与世无争的帅哥 提交于 2019-12-11 05:46:07

问题


I have data

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

how to get output like

psx/ge/eg = 10
sx/sxl/sz = 20

and this is my sytax

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

回答1:


Try this

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

Result

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

Demo: http://rextester.com/WYAJ22189




回答2:


Try this:

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


来源:https://stackoverflow.com/questions/50714061/xml-path-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!