22,209
社区成员
发帖
与我相关
我的任务
分享
declare @table table (ID varchar(3),QTY int)
insert into @table
select '001',20 union all
select '002',20 union all
select '003',35 union all
select '003',5 union all
select '004',10 union all
select '004',1
select t.*,新列=case when row_number() over (partition by t.ID order by t.ID )<>1
and m.ID is not null then ''
else cast((select sum(QTY) from @table where ID=t.ID) as varchar(10)) end
from @table t left join (select ID from @table group by ID having(count(*)>1)) m
on t.ID=m.ID order by m.ID,QTY
/*
ID QTY 新列
---- ----------- ----------
001 20 20
002 20 20
003 5
003 35 40
004 1
004 10 11
*/
create table #tb(num int identity(1,1) ,ID varchar(20), QTY int)
insert into #tb
select
'001', '20'
union
select
'002', '20'
union
select
'003', '35'
union
select
'003', '5'
union
select
'004', '10'
union
select
'004', '1'
select a.*,(case when a.num =(select max(num) from #tb where id = a.id) then b.xinlie else null end) as xinlie
from #tb a left join
(select id,sum(QTY)as xinlie from #tb group by id) b
on a.id = b.id