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 (保潔費,材料費,電費,服務費,寬帶,其餘,燃氣費,水費,維修費,衛生,物業費,押金,優惠,有線電視,租金) )a where CodeCategory_ID=138