create table b2(title1 varchar(20),title2 varchar(20),money int)
insert into b2 select '费用','水费' ,50
union all select '费用','车费' ,30
union all select '费用','车费' ,20
union all select '费用','电费' ,20
select money,
水费=(case when title2='水费' then money else 0 end),
车费=(case when title2='车费'then money else 0 end),
电费=(case when title2='电费' then money else 0 end)
from b2
drop table b2
select [money],
(case title2 when '水费' then [money] else null end) as '水费',
(case title2 when '车费' then [money] else null end) as '车费',
(case title2 when '电费' then [money] else null end) as '电费'
from table1
where Title1='费用'
--测试环境
create table t (Title1 varchar(10),Title2 varchar(10),Money int)
insert into T select '收入','A',100
union all select '费用','水费',50
union all select '费用','车费',30
union all select '费用','车费',20
union all select '费用','电费',80
--动态SQL
declare @s varchar(800)
set @s='select Money '
select @s=@s+',['+Title2+']=max(case when Title2='''+Title2+''' then Money else NULL end) '
from T where Title1='费用'
group by Title2
set @s=@s+' from T group by Money'
exec(@s)
--结果
select [money],
[水费]=(case title2 when '水费' then [money] else 0 end),
[车费]=(case title2 when '车费' then [money] else 0 end),
[电费]=(case title2 when '电费' then [money] else 0 end)
from table1
where Title1='费用'
select [money],
[水费]=(case when [Title2]='水费' then [money] else null end),
[车费]=(case when [Title2]='车费' then [money] else null end),
[电费]=(case when [Title2]='电费' then [money] else null end)
from 表