declare @s varchar(8000)
set @s=''
select @s=@s+',['+c_month+']=sum(case c_month when '''+c_month+''' then c_money end)' from tb_Test group by c_month
exec ('select c_filiable '+@s+' from tb_Test group by c_filiable')
--测试环境
Create table T_Test(c_Filiale varchar(10),c_Month varchar(10),i_Money int)
insert into T_Test select '广东','200501',100
union all select '广东','200502',200
union all select '广东','200503',300
union all select '上海','200501',120
union all select '上海','200502',220
union all select '上海','200503',320
--查询
select 地区=c_Filiale,
[200501]=sum(case when c_Filiale=A.c_Filiale and c_Month='200501' then i_Money end),
[200502]=sum(case when c_Filiale=A.c_Filiale and c_Month='200502' then i_Money end),
[200503]=sum(case when c_Filiale=A.c_Filiale and c_Month='200503' then i_Money end)
from T_Test A
group by c_Filiale
--动态SQL
declare @s varchar(2000)
set @s='select 地区=c_Filiale'
select @s=@s+',['+c_Month+']=sum(case when c_Month='''+c_Month+''' then i_Money end )'
from T_Test A
group by c_Month
set @s=@s+' From T_Test Group by c_Filiale'
exec(@s)
select 地区=c_Filiale,
[200501]=sum(case when c_Filiale=A.c_Filiale and c_Month='200501' then i_Money end),
[200502]=sum(case when c_Filiale=A.c_Filiale and c_Month='200502' then i_Money end),
[200503]=sum(case when c_Filiale=A.c_Filiale and c_Month='200503' then i_Money end)
from T_Test A
group by c_Filiale
select c_Filiale,[200501]=isnull(sum(case when c_Month='200501' then i_Money end),0),
[200502]=isnull(sum(case when c_Month='200502' then i_Money end),0),
[200503]=isnull(sum(case when c_Month='200503' then i_Money end),0)
from tb_Test group by c_Filiale order by c_Filiale