假设有销量表tb_sales
数据如下:
年份 /月份/销量
要显示的效果
SQL Server中:
declare @s nvarchar(1000)
select @s = 'select [name] as 姓名'
select @s = @s + ',sum(case when subject=''' + [subject] + ''' then result else 0 end) as ' + [subject] from dbo.CJ group by [subject]
select @s = @s + ' from CJ group by [name]'
exec(@s)
其他sql语句如下
YEARS 年份,MON月份,SALE销量
select
s.YEARS 年份,
sum(case s.MON when 1 then s.SALE else 0 end) 1月,
sum(case s.MON when 2 then s.SALE end) 2月,
sum(case s.MON when 3 then s.SALE end) 3月,
sum(case s.MON when 4 then s.SALE end) 4月,
sum(case s.MON when 5 then s.SALE else 0 end) 5月
from tb_sales as s group by s.YEAR