1.先創(chuàng)建一個簡單的表product
1 create table product
2 (
3 序號 int identity(1,1) primary key,
4 ProductName varchar(20),
5 productType varchar(20)6 )
2.簡單地插入一些數(shù)據(jù)
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
結(jié)果圖:
完成了,希望能幫到你!