sql data row to column

select CodeName FROM CodeDictionary where CodeCategory_ID=138
结果:

 

 
  
开始转换:
DECLARE
@sql VARCHAR(8000) SELECT @sql=isnull(@sql+',','')+CodeName FROM CodeDictionary where CodeCategory_ID=138 GROUP BY CodeName SET @sql='select * from (select ch.HousebillID,ch.Chargeamount,cd.CodeCategory_ID,cd.CodeName from Housebill hb left join Chargebill ch on hb.ID=ch.HousebillID left join CodeDictionary cd on ch.Chargeitem=cd.ID where cd.CodeCategory_ID=138) tb pivot (max(tb.Chargeamount) for tb.CodeName in ('+@sql+'))a' exec(@sql)

 

结果就类似这样的语句:
select
* from ( select ch.HousebillID,ch.Chargeamount,cd.CodeCategory_ID,cd.CodeName from Housebill hb left join Chargebill ch on hb.ID=ch.HousebillID left join CodeDictionary cd on ch.Chargeitem=cd.ID where cd.CodeCategory_ID=138 ) tb pivot ( sum (tb.Chargeamount) for tb.CodeName in (cleaning fee, material fee, electricity fee, service fee, broadband, other, gas fee, water fee, maintenance fee, sanitation, property fee, deposit, discount, cable TV ,rent) )a where CodeCategory_ID=138

 

 
  
 
  

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325232279&siteId=291194637