SQL多条记录分组合成⼀条数据
要求:1.回车空格消除。
2.进展情况相同的要去重
字符串截取 sql 3.⽅括号内容要消除
4.按年、⽉、任务编码合并成⼀条数据
--创建该函数 nsc_StrSplit 传⼀个值并按‘]’分隔成多条记录存到⼀个表⾥
CREATE FUNCTION [dbo].[nsc_StrSplit] ( @str VARCHAR(4000) )
RETURNS @tableName TABLE ( str2table VARCHAR(4000) )
AS
BEGIN
--SET @str = @str + ','
DECLARE @insertStr VARCHAR(4000) --截取后的第⼀个字符串
DECLARE @newstr VARCHAR(4000) --截取第⼀个字符串后剩余的字符串
SET @insertStr = LEFT(@str, CHARINDEX(']', @str) - 1)
SET @newstr = STUFF(@str, 1, CHARINDEX(']', @str), '')
INSERT @tableName
VALUES ( @insertStr )
WHILE ( LEN(@newstr) > 0 )
BEGIN
SET @insertStr = LEFT(@newstr, CHARINDEX(']', @newstr) - 1)
INSERT @tableName
VALUES ( @insertStr )
SET @newstr = STUFF(@newstr, 1, CHARINDEX(']', @newstr), '')
END
RETURN
END
GO
create table #jzztmx(
id int identity(1,1),
iyear numeric(20, 0),
imonth numeric(20, 0),
rwbm nvarchar(500),
ggjzqk nvarchar(4000)
)
insert into #jzztmx
--2.将【】内容删除再去重
select distinct iyear,imonth,rwbm,substring(mss,0,CHARINDEX('[',mss) ) ggjzqk
from (
--1.将进展状态⾥按】分割成多条数据存到⼀个表⾥并消除回车换⾏,
SELECT iyear,imonth,rwbm,replace(replace(str2table,CHAR(13),''),CHAR(10),'') mss
FROM (select iyear,gjyf imonth,rwbm,jzqk from NSC_A8_shijigenjin where (sfsc !='删除' or sfsc is n
ull) and iyear = @iyear and gjyf <=@imonth ) a OUTER APPLY nsc_StrSplit(a.jzqk) ) a order by rwbm
--按年⽉任务编码合成⼀条记录
select iyear,imonth,rwbm,
jzqk=(
(select ltrim(ggjzqk) +'' from #jzztmx where iyear=a.iyear and imonth=a.imonth and rwbm =a.rwbm
for xml path(''))
) into #jzztzx
from #jzztmx a group by iyear,imonth,rwbm
结果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论