1、原表test结构如下:
2、我们想要得到的结果为:
3、第一种方法:静态方法,即列固定
SQL如下:
select * from ( SELECT date,name,sum(num) num FROM test GROUP BY date,name ) t pivot ( sum(num) for t.name in ([alan],[andy],[baicl])) as a
4、第二种方法:动态方法,即列为通过SQL查询获取
SQL如下:
declare @sql nvarchar(4000) select @sql=isnull(@sql+‘,‘,‘‘)+t.name from (select distinct quotename(name) as name from test) t set @sql=‘select * from (SELECT date,name,sum(num) num FROM test GROUP BY date,name) t pivot ( sum(num) for t.name in (‘[email protected]+‘)) as a‘ exec(@sql)
时间: 2024-11-07 13:49:49