日期:2014-05-18  浏览次数:20465 次

含有多重含义字段的纵横表切换
TA表如下:商品销售和退货在一起,用vtype区别:30表示退货,31表示销售

HTML code
proname     qty     vtype  
AA          -10      30
AA          21       31
AA          12       31
AA          -2       30
BB          -1       30
BB          90       31  
...    

用Sql怎么切换成

HTML code
proname   xssl    xtsl
 AA       33      -12
 BB       90       -1
... 

期望高手帮忙

------解决方案--------------------
SQL code

go
declare @str varchar(max)
set @str=''
select @str=@str+','+'['+LTRIM([vtype])+']'+'=sum(case when [vtype]='+
ltrim([vtype])+' then [qty] else 0 end)'
from tbl group by [vtype]
print @str
exec('select [proname]'+@str+' from tbl group by [proname]')
/*
proname    30    31
AA    -12    33
BB    -1    90
*/