天天看點

多行合并2列并去掉重複列。

create table tb(col1 varchar(10),col2 varchar(10),col3 varchar(10),col4 varchar(10))
go
insert tb select '11111' ,   '222' ,      'A'  ,    1 
insert tb select '1111' ,   '333' ,       'A' ,     1 
insert tb select '2222' ,   '999' ,       'B' ,     2 
insert tb select '3333'  ,  '111' ,       'B' ,     2 
go
create FUNCTION dbo.f_str(@col3 varchar(10))
RETURNS varchar(8000)
AS
BEGIN
declare @str varchar(8000)
set @str=''
select  @[email protected]+case when charindex(','+col1+'-',','[email protected]+'-')=0  then col1+'-' else '' end
+case when charindex('-'+col2+',','-'[email protected]+',')=0  then col2+',' else '' end
from tb where [email protected]
return left(@str,len(@str)-1)
END
go
select distinct newcol=dbo.f_str(col3),col3,col4  from tb       
/*
newcol                      col3  col4
--------------------------------------
11111-222,1111-333   A       1
2222-999,3333-111    B        2
*/
drop table tb
drop function f_str