select b.*, b.model_ent_name+cast(m.year as varchar)as modelname, m.index_value as val into #tb from ( select a.*,erm.model_ent_name from (select w.uuid,w.indexdef_id, i.index_name, i.index_def, case when w.years=2014 then w.actual_value else 0 end as k1, case when w.years=2013 then w.actual_value else 0 end as k2, case when w.years=2012 then w.actual_value else 0 end as k3, case when w.years=2011 then w.actual_value else 0 end as k4, case when w.years=2010 then w.actual_value else 0 end as k5 from bm_work w,bm_index i where w.indexdef_id=i.uuid and w.ent_id='2c90e4da49514c750149515eb56f0003' and w.summary_state=2 and years=2014 )a left join bm_ent_rel_me erm on a.uuid=erm.bmwork_id )b left join bm_model_ent m on b.indexdef_id=m.index_def_id and b.model_ent_name=m.model_ent_name declare @sql varchar(8000) select @sql=isnull(@sql+',','')+modelname from #tb group by modelname set @sql = 'select * from #tb pivot (sum(val) for modelname in ('+@sql+') )a' exec (@sql) drop table #tb
需要將上圖變為下圖結果。
實現行轉列,及把第一張圖片中紅圈的部分的內容放置到 列上,作為列的標題。。。
declare @sql varchar(8000) select @sql=isnull(@sql+',','')+modelname from #tb group by modelname set @sql = 'select * from #tb pivot (sum(val) for modelname in ('+@sql+') )a' //val 為值 modelname為需要將行轉列 exec (@sql)
//寫這種sql的思路就是,先自己寫出類似圖一 的結果,確定那一個需要行轉列。。這裡我們就是需要modelname 這一列的值,都放過去作為列的屬性名。。。看圖兩個圈的描述吧。具體本人也不是很好描述。