declare @sql varchar(8000)
set @sql=''select @sql=@sql+',['+prodType+']=sum(case prodType when '''+prodType+''' then cost else 0 end)'
from 表2 group by prodTypeset @sql='select custNo'+@sql+' from 表1 a,表2 b where a.prodName=b.prodName group by custNo'
exec(@sql)
set @sql=''select @sql=@sql+',['+prodType+']=sum(case prodType when '''+prodType+''' then cost else 0 end)'
from 表2 group by prodTypeset @sql='select custNo'+@sql+' from 表1 a,表2 b where a.prodName=b.prodName group by custNo'
exec(@sql)
insert #tmp select custNo,prodType,sum(cost) cost
from (select a.custNo,a.name,a.cost,a.prodName,b.prodType
from 表1 a inner join 表2 b on a.prodName=b.prodName) c
group by custNo,prodType order by custNo
select distinct a.custNo,(select cost from #tmp where custNo=a.custNo and prodType='食物') 食物,
(select cost from #tmp where custNo=a.custNo and prodType='日用品') 日用品
from #tmp a inner join (select distinct custNo from 表1) b on a.custNo=b.custNo
drop table #tmp