select '收入' as 项目
, case when 项目='一厂本月' then 收入 else null end as 一厂本月
, case when 项目='一厂本年' then 收入 else null end as 一厂本年
, case when 项目='二厂本月' then 收入 else null end as 二厂本月
, case when 项目='二厂本年' then 收入 else null end as 二厂本年
, case when 项目='三厂本月' then 收入 else null end as 三厂本月
, case when 项目='三厂本年' then 收入 else null end as 三厂本年
from 表名
union all
select '成本' as 项目
, case when 项目='一厂本月' then 成本 else null end as 一厂本月
, case when 项目='一厂本年' then 成本 else null end as 一厂本年
, case when 项目='二厂本月' then 成本 else null end as 二厂本月
, case when 项目='二厂本年' then 成本 else null end as 二厂本年
, case when 项目='三厂本月' then 成本 else null end as 三厂本月
, case when 项目='三厂本年' then 成本 else null end as 三厂本年
from 表名
union all
select '其他费用' as 项目
, case when 项目='一厂本月' then 其他费用 else null end as 一厂本月
, case when 项目='一厂本年' then 其他费用 else null end as 一厂本年
, case when 项目='二厂本月' then 其他费用 else null end as 二厂本月
, case when 项目='二厂本年' then 其他费用 else null end as 二厂本年
, case when 项目='三厂本月' then 其他费用 else null end as 三厂本月
, case when 项目='三厂本年' then 其他费用 else null end as 三厂本年
from 表名
union all
select '毛利' as 项目
, case when 项目='一厂本月' then 毛利 else null end as 一厂本月
, case when 项目='一厂本年' then 毛利 else null end as 一厂本年
, case when 项目='二厂本月' then 毛利 else null end as 二厂本月
, case when 项目='二厂本年' then 毛利 else null end as 二厂本年
, case when 项目='三厂本月' then 毛利 else null end as 三厂本月
, case when 项目='三厂本年' then 毛利 else null end as 三厂本年
from 表名
改动态脚本(只改项目,即改原表行不定,列数目固定):
declare @sql nvarchar(max)
set @sql=''
set @sql=@sql+'
select ''收入'' as 项目
'
select @sql=@sql+', case when 项目='''+项目+''' then 收入 else null end as '+项目
from 表名
set @sql=@sql+'
from 表名
'
set @sql=@sql+'union all
select ''成本'' as 项目
'
select @sql=@sql+', case when 项目='''+项目+''' then 成本 else null end as '+项目
from 表名
set @sql=@sql+'
from 表名
'
set @sql=@sql+'union all
select ''其他费用'' as 项目
'
select @sql=@sql+', case when 项目='''+项目+''' then 其他费用 else null end as '+项目
from 表名
set @sql=@sql+'
from 表名
'
set @sql=@sql+'union all
select ''毛利'' as 项目
'
select @sql=@sql+', case when 项目='''+项目+''' then 毛利 else null end as '+项目
from 表名
set @sql=@sql+'
from 表名
'
exec sp_executesql @sql
改动态脚本(改原表行和列数目不固定,两层动态脚本,能实现但基本难读):
declare @sql nvarchar(max)
set @sql='declare @sql_in nvarchar(max)
set @sql_in='' '' '
set @sql=@sql+'select @sql_in=@sql_in+''union all
select ''''''+name+'''''' as 项目
'
select @sql=@sql+', case when 项目='''''+项目+''''' then ''+name+'' else null end as '+项目
from 表名
set @sql=@sql+'
from 表名
''
from syscolumns where id=(select id from sysobjects where name=''表名'')
order by colorder
set @sql_in=stuff(@sql_in,1,10,'''')
exec sp_executesql @sql_in
'
exec sp_executesql @sql
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)