同一主表,明细不同数据进行合并

对明细中的同一主键ID相关数据进行合并

1.主表的【项目】+明细表的【附加项目】 

2.明细表的金额

数据源

if object_id('tempdb..#主表') is not null drop table tempdb..#主表
if object_id('tempdb..#细表') is not null drop table tempdb..#细表


select 1 主键, 'a' 项目, 3000 金额, 3210 小计金额  into #主表 union all
select 2, 'a', 4500, 5000 union all
select 3, 'a', 600, 680 union all
select 4, 'a', 1400, 1600

select 1 主表主键, 'wms' 附加项目, 10 单价, 140 金额 into #细表 union all
select 1, 'oms', 5, 70 union all          
select 2, 'crm', 20, 400 union all
select 2, '综合', 5, 100 union all
select 3, 'crm', 20, 80 union all
select 4, 'crm', 20, 200

 

方法1 使用case when 表达式 then 赋值 esle end 

if object_id('tempdb..#目标细表') is not null drop table tempdb..#目标细表
select 主表主键,cast(附加项目 as varchar(300)) 附加项目,单价,金额 into #目标细表 from #细表

declare @主表主键 varchar(max)='',@附加项目 varchar(max)=''
update a  
set @附加项目=case when @主表主键=主表主键 then isnull(@附加项目,'')+isnull(附加项目,'') 
                   else isnull(附加项目,'') 
                   end
,@主表主键=a.主表主键
,附加项目=isnull(@附加项目,'') from #目标细表 a

;with it
as(
select 主表主键,max(附加项目) 项目,sum(金额) 附加金额 from #目标细表 a 
group by 主表主键 
)
select a.项目+b.项目 项目,金额,小计金额,附加金额 
from #主表 a join it  b on a.主键=b.主表主键 

执行结果

 

方法2 使用行转列的方法 动态sql

if object_id('tempdb..#目标细表') is not null drop table tempdb..#目标细表
select
主表主键,附加项目,单价,金额 , rn = row_number() over(partition by 主表主键 order by 主表主键) into #目标明细 from #细表 declare @sql varchar(max)='',@sql2 varchar(max)='',@fiede varchar(max)='' select @fiede =@fiede+'附加项目'+cast(rn as varchar(10))+'+' from #目标明细 group by rn set @fiede=left(@fiede,len(@fiede)-1) select @sql='select 主表主键' select @sql=@sql+' , isnull(max(case rn when '''+cast(rn as varchar(10))+''' then 附加项目 end ),'''') 附加项目'+cast(rn as varchar(10))+' , isnull(max(case rn when '''+cast(rn as varchar(10))+''' then 金额 end ),0) 金额'+cast(rn as varchar(10))+' ' from #目标明细 group by rn select @sql=@sql+' into #统计结果 from #目标明细 group by 主表主键' print @sql set @sql2 =' select a.项目+'+@fiede+' 项目,a.金额,a.小计金额,a.小计金额-a.金额 附加金额 from #主表 a join #统计结果 b on a.主键=b.主表主键 ' set @sql=@sql+@sql2 exec(@sql)

 

 

执行结果

posted @ 2014-08-25 16:47  起航Fly  阅读(877)  评论(0编辑  收藏  举报