--創建測試數據
create?table?tt6?([藥品名]?varchar(20),[銷售量]?int,?[售往]?varchar(20));
insert?into?tt6
select?'0002',32,'病房'?union?all
select?'0002',30,'西藥房'
GO
--創建字符串聚合函數
if?object_id(N'dbo.fn_merge_tt6',N'FN')?is?not?null?
drop?function?dbo.fn_merge_tt6?
GO?
create?function?dbo.fn_merge_tt6
--函數功能:字符串聚合及去除重復值?
--詳細出處參考:
(?
@id?varchar(100),
@separateStr?varchar(20)--分隔符
)?
returns?varchar(8000)?
as?
begin?
--字符串聚合
declare?@s?varchar(8000)?
set?@s?=?''
select?
@s?=?@s?+?[售往]?+?@separateStr?
from?tt6?
where?[藥品名]?=?@id
--去除重復值
declare?@value?varchar(8000)--存儲第壹個分隔符前的值?
declare?@result?varchar(8000)--存儲唯壹值的中間字符串?
set?@result?=?''?
--有值的場合?
while?charindex(@separateStr,@s)?<>?0?
begin?
--取第壹個分隔符前的值? set?@value?=?left(@s,charindex(@separateStr,@s)-1)? --第壹個分隔符前的值沒在結果中出現? if?charindex(@separateStr+@value+@separateStr,@separateStr+@result+@separateStr)=0? begin?--加入中間字符串?
set?@result?=?@result?+?@value?+?@separateStr?
end? --去除第壹個值以及最後面的分隔符(剔除法),繼續循環判斷? set?@s?=?right(@s,(len(@s)?-?charindex(@separateStr,@s)-len(@separateStr)+1))end?
set?@s?=?@result;
return?left(@s,len(@s)-len(@separateStr));
end?
GO
--查詢
select?[藥品名],sum(銷售量)?[銷售量],dbo.fn_merge_tt6([藥品名],'\')?[售往]?
from?tt6?group?by?[藥品名]
最後結果如下: