iT邦幫忙

0

[MSSQL] 字串相加 欄位合併-FOR XML PATH

  • 分享至 

  • xImage
  •  

這些國家,哪些天有比賽?

準備資料

drop table #UEFO_Country
CREATE TABLE #UEFO_Country
(
	name varchar(30)
	,rundate int
)

insert into #UEFO_Country
values	('German',20180101)
		,('Spain',20180102)
		,('France',20180103)
		,('France',20180105)
		,('Italy',20180104)		
		,('Italy',20180106)
		,('Italy',20180107)


select name  from #UEFO_Country

https://ithelp.ithome.com.tw/upload/images/20180130/20106764azczFgBShX.png

字串相加方法1

declare   @String varchar(8000)=''
select @String=@String +'.'+name  from #UEFO_Country
select @String

https://ithelp.ithome.com.tw/upload/images/20180130/20106764RIKl19LRy1.png

字串相加方法2-FOR XML PATH

select name,	
(
	SELECT cast(rundate AS NVARCHAR ) + '.' 
    from #UEFO_Country  	
	where name=t0.name	--把name一樣的加起來
	FOR XML PATH('')
) as DateList
from #UEFO_Country t0

過濾重複資料-使用 DISTINCT 語法

select DISTINCT  name,
datelist=
(
	SELECT cast(rundate AS NVARCHAR ) + '.' 
    from #UEFO_Country  	
	where name=t0.name	--把name一樣的加起來
	FOR XML PATH('')
)
from #UEFO_Country t0

https://ithelp.ithome.com.tw/upload/images/20180130/20106764U9rvpgpuG1.png

過濾重複資料-使用GROUP 語法

select name,datelist  from 
(
	select name,
	datelist=
	(
		SELECT cast(rundate AS NVARCHAR ) + '.' from #UEFO_Country  	
		where name=t0.name	--把name一樣的加起來
		FOR XML PATH('')
	)
	from #UEFO_Country t0
) a
group by name,datelist 
order by datelist 

拆字串

SELECT * FROM STRING_SPLIT('England,Spain,Japan', ',') --for SQL Server 2016

REF
https://dotblogs.com.tw/supershowwei/2016/01/26/145353
https://dotblogs.com.tw/stanley14/2017/03/27/string_split_merge


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言