1.先创建一个简单的表product
1 create table product
2 (
3 序号 int identity(1,1) primary key,
4 ProductName varchar(20),
5 productType varchar(20)6 )
2.简单地插入一些数据
1 insert product values('羊羊鞋','L')
2 insert product values('羊羊鞋','XL')
3 insert product values('羊羊鞋','XXL')
4 insert product values('羊羊鞋','XXXL')
5
6 insert product values('XX衬衫','L')
7 insert product values('XX衬衫','XL')
8 insert product values('XX衬衫','XXL')
3.下面是CTE
1 with cte (ProductName,productType)
2 as
3 (
4 select ProductName,min(productType) from product
5 group by ProductName
6 union all
7 select p.ProductName,convert(varchar(20),p.productType+','+c.productType) from product p
8 inner join cte c on c.ProductName=p.ProductName
9 where p.ProductName=c.ProductName and p.productType>c.productType
10 )
11 select ProductName,max(productType)productType from cte
12 group by ProductName
结果图:
完成了,希望能帮到你!