如何在文本字段上聚合?

时间:2018-02-13 22:41:35

标签: sql sql-server

我想在ProductID上汇总并将所有成分附加到该ProductID的汇总行中。 ProductID是" GROUP BY",可以在Ingredient字段上使用什么运算符。

这不是数据仓库。我知道STRING_AGG在SQL Server 2017中可用,我也没有,我有SQL Server 2012。

enter image description here

2 个答案:

答案 0 :(得分:0)

使用xml示例中的内容尝试一下你可能正在寻找的东西..

;with mycte as (
select '100' as product, 'a' as ingredient
union all
select '100' as product, 'b' as ingredient
union all
select '100' as product, 'c' as ingredient
union all
select '200' as product, 'd' as ingredient
union all
select '200' as product, 'e' as ingredient
union all
select '200' as product, 'f' as ingredient
)

select distinct
 product ,
stuff((select ','+ingredient
from mycte mycte1
where mycte1.product=mycte.product
for xml path('')),1,1,'') as ingredient_list

 from mycte 

结果集

product  ingredient_list
100      a,b,c
200      d,e,f

答案 1 :(得分:0)

另一种选择,在函数中使用循环:

create function [dbo].[GetIngredients](@ProductID int)
returns varchar(max)
begin
declare @result varchar(max), @ingredient varchar(100)
set @ingredient=''
set @result=''
while exists(select * from vBobbyTables where ProductID=@ProductID 
  and ingredient>@ingredient)
begin
  set @ingredient=(select min(ingredient) from vBobbyTables where ProductID=@ProductID 
    and Ingredient> @ingredient)
  if @result<>''
    set @result=@result+','
  set @result=@result+@ingredient
end
return @result
end

然后在您的选择中调用它:

select productid, dbo.getingredients(productid)
from vBobbyTables
group by productid