行列转换后的求和问题
原表
转换后
执行行列转换后,我需要对每个收费项目进行求和,这个时候我的SQL语句应该怎么写?
(因为收费项目是动态变化的,没办法确定 ,所以无法
用 insert into () select sum() 的方式
)
下面是我写的SQL语句
declare @sql varchar(8000)
select @sql=isnull(@sql+',','') +'sum(case when SFXM_SFXMMC='''+SFXM_SFXMMC+''' then SKJE else 0 end) as ['+SFXM_SFXMMC+']'
from (select distinct SFXM_SFXMMC from BB_RSFQDCZKJ_Second ) t
ORDER BY SFXM_SFXMMC
exec ('select FJDA_FJID 房间代码,FJDA_FJMC 房间名称,jkr AS 租户名称, SKR 收款人,FJDA_JZMJ 建筑面积,
tzrq 实收日期, fyqj 缴费期间,YS AS 缴费月数,skfs 收款方式 ,PZH 凭证号码,
SUM(SKJE) 合计,'+@sql+'into BB_RSFQDCZKJ_first from BB_RSFQDCZKJ_Second
group by FJDA_FJID ,FJDA_FJMC ,jkr,SKR,FJDA_JZMJ ,tzrq , fyqj ,YS ,skfs ,PZH')
declare @sql varchar(8000),@sql2 varchar(8000)
select @sql=isnull(@sql+',','') +'sum(case when SFXM_SFXMMC='''+SFXM_SFXMMC+''' then SKJE else 0 end) as ['+SFXM_SFXMMC+']'
from (select distinct SFXM_SFXMMC from BB_RSFQDCZKJ_Second) t
order by SFXM_SFXMMC
select @sql2=isnull(@sql2+',','')+'sum(['+SFXM_SFXMMC+']) as ['+SFXM_SFXMMC+']'
from (select distinct SFXM_SFXMMC from BB_RSFQDCZKJ_Second) t
order by SFXM_SFXMMC
exec ('select FJDA_FJID 房间代码,FJDA_FJMC 房间名称,jkr AS 租户名称, SKR 收款人,FJDA_JZMJ 建筑面积,
tzrq 实收日期, fyqj 缴费期间,YS AS 缴费月数,skfs 收款方式 ,PZH 凭证号码,
SUM(SKJE) 合计,'+@sql
+'into BB_RSFQDCZKJ_first
from BB_RSFQDCZKJ_Second
group by FJDA_FJID ,FJDA_FJMC,jkr,SKR,FJDA_JZMJ ,tzrq,fyqj,YS,skfs,PZH;
select '+@sql2+' from BB_RSFQDCZKJ_first')