首页 > 代码库 > sql 理解
sql 理解
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)
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 这一列的值,都放过去作为列的属性名。。。看图两个圈的描述吧。具体本人也不是很好描述。
sql 理解
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。