sql语句问题
表A:
Name Type Value
小张 销售 100
小王 采购 150
小李 销售 200
小张 采购 100
请用sql实现并显示以下结果:
Name 采购 销售
小张 100 100
小李 0 200
小王 150 0
------解决方案--------------------Name Type Value
小张 销售 100
小王 采购 150
小李 销售 200
小张 采购 100
select Name ,sum(case when Type = '销售 ' then Value else 0 end) 销售,
sum(case when Type = '采购 ' then Value else 0 end) 采购
from 表 group by Name
------解决方案--------------------declare @sql varchar(8000)
set @sql = 'select name, '
select @sql = @sql + 'sum(case Type when ' ' '+Type+ ' ' '
then Value else 0 end) as ' ' '+Type+ ' ' ', '
from (select distinct Type from 表A) as a
select @sql = left(@sql,len(@sql)-1) + ' from 表A group by name '
exec(@sql)
go
Type 不确定就这样
------解决方案--------------------Create Table B
(name char(10),type char(4),value int)
Insert B Select '小张 ', '销售 ', 100
Union All Select '小王 ', '采购 ', 150
Union All Select '小李 ', '销售 ', 200
Union All Select '小张 ', '采购 ', 100
select name,sum(case when type= '销售 ' then value else 0 end) as 销售,
sum(case when type= '采购 ' then value else 0 end) as 采购 from b group by name
drop table b