34,837
社区成员




create table #t(person_id varchar(20), item_type varchar(20),金额 int)
insert #t select 'p101','增项',50 union all
select 'p101','减项',10 union all
-- select 'p101','增项合计',0 union all
select 'p102','增项',10 union all
select 'p102','减项',30-- union all
-- select 'p102','增项合计',0
go
select *
from (
select * from #t
union
select person_id ,'合计' as item_type,sum(case when item_type = '增项' then 金额 else -1 * 金额 end)
from #t group by person_id) a
order by person_id ,case when item_type = '合计' then 1 else 0 end
drop table #t
/*
person_id item_type 金额
-------------------- -------------------- -----------
p101 减项 10
p101 增项 50
p101 合计 40
p102 减项 30
p102 增项 10
p102 合计 -20
(所影响的行数为 6 行)
*/
create table #t(person_id varchar(20), item_type varchar(20),金额 int)
insert #t select 'p101','增项',10 union all
select 'p101','减项',10 union all
-- select 'p101','增项合计',0 union all
select 'p102','增项',10 union all
select 'p102','减项',10-- union all
-- select 'p102','增项合计',0
go
select *
from (
select * from #t
union
select person_id ,'合计' as item_type,sum(case when item_type = '增项' then 金额 else -1 * 金额 end)
from #t group by person_id) a
order by person_id ,case when item_type = '合计' then 1 else 0 end
drop table #t
/*
person_id item_type 金额
-------------------- -------------------- -----------
p101 减项 10
p101 增项 10
p101 合计 0
p102 减项 10
p102 增项 10
p102 合计 0
(所影响的行数为 6 行)
*/
create table #t(person_id varchar(20), item_type varchar(20),金额 int)
insert #t select 'p101','增项',10 union all
select 'p101','增项',10 union all
select 'p101','增项合计',0 union all
select 'p102','增项',10 union all
select 'p102','增项',10 union all
select 'p102','增项合计',0
update #t
set #t.金额= a.总金额
from (select person_id, sum(金额) 总金额 from #t
group by person_id) a
where a.person_id = #t.person_id and #t.item_type = '增项合计'
--select * from #t
/*结果
p101 增项 10
p101 增项 10
p101 增项合计 20
p102 增项 10
p102 增项 10
p102 增项合计 20
*/
--drop table #t
--drop table #tmp
update a set a.金额 = b.summoney
from x as a,
(select person_id,sum(金额) summoney from x where item_type = '增项' group by person_id) as b
where a.item_type='增项合计' and a.person_id = b.person_id
select person_id,item_type,合计=sum(金额) from x group by person_id,item_type having item_type='增项'