sql server行转列
declare @sql varchar(8000)
set @sql = 'select d.sBillNo,g.goodsId ';
SELECT @sql = @sql + ',''' + g.GoodName + '''=isnull(sum(case g.GoodName when ''' + g.goodName + ''' then d.Qty end),0)'
from (
SELECT distinct g.goodsId, g.GoodName FROM BS_GoodsInfo g
inner join BS_dSaleBill d on g.CompanyId = d.CompanyId and g.GoodsId = d.GoodsId and d.CompanyId = '002' --WHERE ID >20 AND ID < 100
) as g
execute(@sql + 'FROM BS_dSaleBill d inner join BS_GoodsInfo g on g.CompanyId = d.CompanyId and g.GoodsId = d.GoodsId group by g.goodsId,d.sBillNo ')
set @sql = 'select d.sBillNo,g.goodsId ';
SELECT @sql = @sql + ',''' + g.GoodName + '''=isnull(sum(case g.GoodName when ''' + g.goodName + ''' then d.Qty end),0)'
from (
SELECT distinct g.goodsId, g.GoodName FROM BS_GoodsInfo g
inner join BS_dSaleBill d on g.CompanyId = d.CompanyId and g.GoodsId = d.GoodsId and d.CompanyId = '002' --WHERE ID >20 AND ID < 100
) as g
execute(@sql + 'FROM BS_dSaleBill d inner join BS_GoodsInfo g on g.CompanyId = d.CompanyId and g.GoodsId = d.GoodsId group by g.goodsId,d.sBillNo ')