With CTE as
(
Select ProductCategoryId,
Count(*) [Count],
Max(ProductName) ProductNames,
0 [Rank]
From Product
Group By ProductCategoryId
Union ALL
Select CTE.ProductCategoryId,
CTE.[Count],
ProductNames + N' , ' + ProductName,
[Rank]+1
From
CTE inner join Product
on CTE.ProductCategoryId = Product.ProductCategoryId
and CTE.ProductNames Not Like '%'+ProductName+'%'
and CTE.[Rank] < cte.[Count]
)
Select ProductCategoryId,
Max(ProductNames) ProductNames,
Max([Count]) [Count]
From CTE
Group by ProductCategoryId
order by ProductCategoryId
答案 0 :(得分:4)
我之前在递归CTE中的字符串类型上收到此错误。我只是通过将值转换为大字符串来修复它:
Select ProductCategoryId,
Count(*) as [Count],
cast(Max(ProductName) as nvarchar(max)) as ProductNames,
0 as [Rank]
From Product
Group By ProductCategoryId
Union ALL
Select CTE.ProductCategoryId,
CTE.[Count],
cast(ProductNames + N' , ' + ProductName as nvarchar(max)),
[Rank]+1
From
CTE inner join Product
on CTE.ProductCategoryId = Product.ProductCategoryId
and CTE.ProductNames Not Like '%'+ProductName+'%'
and CTE.[Rank] < cte.[Count]